File handling

Introduction

Python's versatility and ease of use make it a popular choice for handling various tasks, including file operations. Whether you're reading data from a file, writing to it, or manipulating its contents, Python provides powerful tools and libraries to streamline the process. In this blog post, we'll explore the fundamentals of file handling in Python, covering everything from opening and closing files to advanced techniques for reading and writing data.

Sections

  • Understanding file handling
  • Access Modes for Reading a file
  • Opening and Closing files
  • Reading from files
  • Writing to files
  • Conclusion
What is mean by Files
  • Each file has a name, like hello.py, mytext.txt or coolimage.png. Usually the name ends with an extension that describes the content, like py for Python, txt for text or png for "portable network graphic".
  • With just names identifying the files, it wouldn't be possible to have two files with the same name. That's why files also have a location. We'll talk more about this in a moment.
  • Files have content that consists of 8-bit bytes.

Directories/folders

Directories are a way to group files. They also have a name and a location like files, but instead of containing data directly like files do they contain other files and directories.

Paths

Directories and files have a path, like C:\Users\me\hello.py. That just means that there's a folder called C:, and inside it there's a folder called Users, and inside it there's a folder called me and inside it there's a hello.py. Like this:

C:
└── Users
└── me
└── hello.py
C:\Users\me\hello.py is an absolute path. But there are also relative paths. For example, if we are in C:\Users, me\hello.py is same as C:\Users\me\hello.py. The place we are in is sometimes called current directory, working directory or current working

Understanding File Handling

File handling in Python involves performing operations such as reading from and writing to files stored on the disk. Python provides built-in functions and methods to facilitate these operations, making it simple to work with files of different formats and sizes.

Access Modes for Reading a File

The key function for working with files in Python is the open() function.
The open() function takes two parameters; filename, and mode. There are four different methods (modes) for opening a file:
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists

Syntax:

f = open("demofile.txt")
Opening and Closing Files

The first step in file handling is opening a file for reading, writing, or both. Python's open() function is used to open a file, specifying the file name and mode ('r' for reading, 'w' for writing, 'a' for appending, and more). It's essential to close the file using the close() method once you're done with it to free up system resources.

python code:

# Open a file for reading
file = open('example.txt', 'r')

 

# Read data from the file 
data = file.read()

 

# Close the file 
file.close()

 

Reading from Files

Python offers various methods for reading data from files, such as read(), readline(), and readlines(). These methods allow you to read the entire file, one line at a time, or all lines into a list, respectively.

The read () is used to return the entire file content and it accepts the optional size parameter that mentions the bytes to read from the file. Once you created the file handle you can read data from it with a separate step. Basically there are 3 very important and useful methods you should know [2]:

  • read()
  • readline()
  • readlines()
read() reads the whole file in once as a string.
readline() only reads a specific line of data (reads the first line by default)
readlines() reads all the lines and returns a list of strings where each string is a line of data
# Read the entire file 
file = open('example.txt', 'r')
data = file.read()
file.close()

 Using the readline() method, we can read a file line by line. by default, this method reads the first line in the file.

# Read one line at a time 
file = open('example.txt', 'r')
line = file.readline()
file.close() 

While we have seen how to extract the entire file contents using the readline() method, we can achieve the same using the readlines() method. This method read file line by line into a list.

# Read all lines into a list
file = open('example.txt', 'r')
lines = file.readlines()
file.close()
 
Writing to Files

To write data to a file, open it in write ('w') or append ('a') mode and use the write() method to write data to the file. You can also use the writelines() method to write a list of lines to the file.

python code:

# Write data to a file 
file = open('output.txt', 'w')
file.write('Hello, World!')
file.close()

 

# Append data to a file 
file = open('output.txt', 'a')
file.write('\nThis is a new line.')
file.close()

 

Handling File Errors

When working with files, it's crucial to handle potential errors gracefully. Python's try-except block can be used to catch and handle exceptions that may occur during file operations.


python code:

try:  
file = open('nonexistent_file.txt', 'r')
data = file.read()
file.close()
except FileNotFoundError:
print("File not found!")
Conclusion

File handling is an essential aspect of programming in Python, enabling developers to read, write, and manipulate data stored in files. By mastering file handling techniques, you can efficiently work with files of various formats and sizes, making Python a powerful tool for data processing, analysis, and manipulation. Whether you're a beginner or an experienced Python programmer, understanding file handling is a valuable skill that will enhance your capabilities and productivity.

 References

1. https://pynative.com/python/file-handling

2-Managing files in Python

Last modified: Friday, 3 May 2024, 7:29 AM