Python File Handling
File handling is an essential aspect of programming that allows you to read from and write to files. This guide will cover the basics of file handling in Python, including how to open, read, write, and close files. We’ll also explore more advanced topics such as working with different file modes, handling exceptions, and using context managers.
The open() function is used to open a file. It returns a file object, which provides methods and attributes to interact with the file.
Syntax
- file_name: The name of the file to be opened.
- mode: The mode in which the file is opened (e.g., ‘r’, ‘w’, ‘a’).
Common File Modes
Mode | Description |
‘r’ | Read (default mode) |
‘w’ | Write (creates a new file or truncates existing) |
‘a’ | Append (adds to the end of the file) |
‘b’ | Binary mode (e.g., ‘rb’, ‘wb’) |
‘t’ | Text mode (default mode, e.g., ‘rt’, ‘wt’) |
Example: Opening and Closing a File
Using the with statement ensures that the file is properly closed after its suite finishes, even if an exception is raised. This is the preferred way to work with files.
Example: Using with Statement
The read() method reads the entire content of the file as a single string.
Example
The readline() method reads one line at a time, and readlines() reads all lines into a list.
Example: Reading Line by Line
Example: Reading All Lines
The write() method writes a string to the file.
Example
The a mode opens the file for appending, adding new content to the end of the file.
Example
Binary files are used to store data in binary format. You can read and write binary files using the rb and wb modes.
Example: Writing Binary Data
Example: Reading Binary Data
It’s important to handle exceptions that may occur during file operations, such as FileNotFoundError or IOError.
Example
Write a program to copy the content of one file to another.
Example
Write a program to count the number of words in a text file.
Example
Write a program to read a file and print each line with a line number.
Example
Write a program to merge the content of two files into a third file.
Example
In this guide, we’ve covered the basics of file handling in Python, including opening, reading, writing, and closing files. We’ve also explored more advanced topics such as working with binary files, handling exceptions, and using context managers. File handling is crucial for working with data stored in files, and mastering these concepts will enhance your programming skills. Practice these concepts with the provided examples and exercises to reinforce your understanding. In the next section, we will delve into object-oriented programming (OOP) in Python, which helps you create modular and reusable code. Happy coding!