File Handling
File Handling
Section titled “File Handling”File handling allows a Python program to interact with files, including reading, writing, and updating them. Python provides a variety of builtin functions and methods to handle files efficiently.

Opening and Closing Files
Section titled “Opening and Closing Files”The built-in open() function is used to open a file. It requires a filename and a mode as arguments and returns a file object. The close() method should always be called when you’re done with the file.
file = open("example.txt", "r") # Opens the file in read mode# ... operations ...file.close() # Closes the fileFile Modes: The mode determines how a file is used. It is specified as a second argument to the open() function.
| Mode | Description |
|---|---|
r | Opens a file for reading only. The file pointer is at the beginning. This is the default mode. |
rb | Opens a file for reading in binary format. |
r+ | Opens a file for both reading and writing. The file pointer is at the beginning. |
rb+ | Opens a file for both reading and writing in binary format. |
w | Opens a file for writing only. It overwrites the file if it exists. If not, it creates a new file. |
wb | Opens a file for writing in binary format. |
w+ | Opens a file for both writing and reading. It overwrites the file if it exists, or creates a new one. |
wb+ | Opens a file for both writing and reading in binary format. |
a | Opens a file for appending. The pointer is at the end of the file. It creates a new file if it doesn’t exist. |
ab | Opens a file for appending in binary format. |
a+ | Opens a file for both appending and reading. The pointer is at the end of the file. It creates a new file if it doesn’t exist. |
ab+ | Opens a file for both appending and reading in binary format. |
Reading and Writing
Section titled “Reading and Writing”Once a file is open, you can read content using these methods:
read(): Reads the entire file content into a single string.readline(): Reads a single line from the file.readlines(): Reads all lines into a list of strings.
To write content, use:
write(string): Writes a single string to the file.writelines(list_of_strings): Writes a list of strings to the file.
The with Statement
Section titled “The with Statement”The with statement is the recommended way to handle files. It automatically closes the file, even if an error occurs, so you don’t have to manually call close().
with open("example.txt", "r") as file: content = file.read() print(content)# The file is automatically closed here