File Handling
File handling in Python allows you to work with files – creating, reading, writing, and closing them. It is an essential feature for tasks like storing data, processing text files, or generating reports.
Opening a File
To work with a file, you first need to open it using the open() function. The syntax is:
file = open(filename, mode)
- filename: The name of the file (e.g., "data.txt").
- mode: Specifies what you want to do with the file.
File Modes
Mode | Description |
---|---|
"r" | Read mode (default). Opens a file for reading. |
"w" | Write mode. Creates a new file or overwrites an existing file. |
"a" | Append mode. Adds data to the end of an existing file. |
"x" | Create mode. Creates a file; raises an error if the file exists. |
"t" | Text mode (default). Reads/writes text. |
"b" | Binary mode. Reads/writes binary data. |
Reading a File
You can read the contents of a file using various methods:
- read(): Reads the entire file.
- readline(): Reads one line at a time.
- readlines(): Reads all lines and returns them as a list.
Examples:
# Example file: "example.txt" contains "Hello\nWorld" # Open the file in read mode file = open("example.txt", "r") # Read the entire content content = file.read() print(content) # Output: Hello\nWorld # Close the file file.close()
Writing to a File
To write data into a file, open it in "w" (write) or "a" (append) mode.
- write(): Writes a string to the file.
- writelines(): Writes a list of strings to the file.
Examples:
# Open a file in write mode file = open("example.txt", "w") # Write data file.write("Hello World") file.close()
# Append data to the file file = open("example.txt", "a") file.write("\nAppended Text") file.close()
Closing a File
Always close a file after you are done with it to free system resources. Use the close() method.
Example:
file = open("example.txt", "r") print(file.read()) file.close()
Using with Statement
Using with ensures the file is automatically closed after you are done with it.
Example:
with open("example.txt", "r") as file: content = file.read() print(content) # File is automatically closed after this block
Checking if a File Exists
Use the os module to check if a file exists.
Example:
import os if os.path.exists("example.txt"): print("File exists!") else: print("File does not exist.")
Working with Text and Binary Files
- Text Files: Use "t" mode (default). Handles strings.
- Binary Files: Use "b" mode. Handles binary data like images.
Example (Binary Mode):
# Copy a binary file (e.g., an image) with open("image.jpg", "rb") as source: with open("copy.jpg", "wb") as destination: destination.write(source.read())
Deleting a File
To delete a file, use the os module's remove() method.
Example:
import os if os.path.exists("example.txt"): os.remove("example.txt") print("File deleted.") else: print("File not found.")
Handling Exceptions
When working with files, it's a good practice to handle exceptions to avoid runtime errors.
Example:
try: file = open("example.txt", "r") print(file.read()) except FileNotFoundError: print("File not found!") finally: if file: file.close()