This tutorial provides a comprehensive guide to file handling in Python. Files are crucial for persistent data storage and retrieval, enabling your programs to interact with data beyond their runtime. We’ll cover fundamental file operations, from opening and closing files to reading, writing, renaming, and deleting them. We’ll also explore best practices for error handling and efficient file management.
Table of Contents:
- Opening Files
- File Objects and Context Managers
- Writing to Files
- Reading from Files
- File System Operations: Renaming and Deleting
- Handling Exceptions
1. Opening Files
The open()
function is the cornerstone of file interaction in Python. It takes the filename (a string) and a mode as primary arguments. The mode determines how the file will be accessed (reading, writing, appending, etc.).
Common modes include:
'r'
: Read (default). Opens for reading. Raises an error if the file doesn’t exist.'w'
: Write. Opens for writing. Overwrites the file if it exists; creates it if it doesn’t.'a'
: Append. Opens for writing. Appends data to the end if the file exists; creates it if it doesn’t.'x'
: Exclusive creation. Creates a new file. Raises an error if the file already exists.'b'
: Binary mode. For non-text files (images, executables). Can be combined with other modes (e.g.,'rb'
,'wb'
).'t'
: Text mode (default). For text files.
# Open a file for writing
file = open("my_file.txt", "w")
# Open a file for reading
file = open("my_file.txt", "r")
# Open a file in binary mode for reading
file = open("image.jpg", "rb")
2. File Objects and Context Managers
open()
returns a file object, providing methods for file interaction. A crucial best practice is using context managers (with
statement) to ensure files are automatically closed, even if errors occur:
with open("my_file.txt", "w") as file:
file.write("This is some text.n") # File automatically closed after this block
with open("my_file.txt", "r") as file:
contents = file.read()
print(contents)
3. Writing to Files
The write()
method writes a string to the file. For writing multiple lines, use n
for newlines.
with open("my_file.txt", "w") as file:
file.write("Line 1n")
file.write("Line 2n")
4. Reading from Files
Several methods read file data:
read()
: Reads the entire file content into a single string.readline()
: Reads a single line.readlines()
: Reads all lines into a list of strings.- Iteration: You can directly iterate over a file object to read lines one by one.
with open("my_file.txt", "r") as file:
contents = file.read()
print(contents)
file.seek(0) # Reset file pointer
line = file.readline()
print(line)
file.seek(0) # Reset file pointer
lines = file.readlines()
print(lines)
file.seek(0) # Reset file pointer
for line in file:
print(line, end="") #end="" prevents extra newline
5. File System Operations: Renaming and Deleting
The os
module provides functions for file system manipulation:
import os
# Rename a file
os.rename("my_file.txt", "new_file.txt")
# Remove a file
os.remove("new_file.txt")
6. Handling Exceptions
Always handle potential exceptions (FileNotFoundError
, IOError
, etc.) when working with files:
try:
with open("my_file.txt", "r") as file:
# ... file operations ...
except FileNotFoundError:
print("File not found.")
except IOError as e:
print(f"An IO error occurred: {e}")