This chapter details how Python interacts with the file system to read and write data. We will focus on the standard methods for file access and the highly recommended, Pythonic practice of using context managers (with statement) for safe file operations.
1. The open() Function and File Modes
The primary function for interacting with files is open(). It returns a file object, which is used to perform read or write operations.
- Syntax:
open(filename, mode)
A. Common File Modes
| Mode | Purpose | Pointer Position | Notes |
r | Read (default) | Beginning | File must exist. Raises FileNotFoundError if not. |
w | Write | Beginning | Creates the file if it doesn’t exist. Overwrites content if it does. |
a | Append | End | Creates the file if it doesn’t exist. Adds new content to the end of the file. |
r+ | Read and Write | Beginning | Allows both reading and writing to an existing file. |
2. Reading and Writing Data
Once a file object is open, you use its methods to interact with the data.
A. Writing Data
The write() method writes a string to the file. It does not automatically add a newline character (\n).
file = open("notes.txt", "w")
file.write("First line of text.\n")
file.write("Second line.")
file.close() # CRUCIAL: Must close the file after use
B. Reading Data
| Method | Description |
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. |
file = open("notes.txt", "r")
content = file.read()
print(content)
file.close()
3. The with Statement (Context Manager)
The most critical principle in file handling is ensuring the file resource is properly closed after use. Failing to close files can lead to data corruption or resource leaks.
The with statement (known as a Context Manager) guarantees that the file’s close() method is automatically called, even if errors occur within the block. This is the recommended, Pythonic way to handle files.
Syntax: with open(filename, mode) as file_object:
# The file is GUARANTEED to be closed automatically upon exiting the 'with' block.
with open("data.txt", "w") as f:
f.write("Safe writing operation.")
# No need for f.close()
Reading Files with with (Iterating Line-by-Line)
File objects are iterable, meaning you can loop directly over the file to read it line by line, which is memory-efficient for large files.
# Reads one line at a time, very efficient for large data
with open("data.txt", "r") as f:
for line in f:
print(line.strip()) # Use strip() to remove the trailing newline character
4. Working with CSV Files (Overview)
The built-in csv module simplifies reading and writing structured comma-separated values (CSV) files.
import csv
# Writing to a CSV file
data = [['Name', 'Age'], ['Alice', 30], ['Bob', 25]]
with open('people.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerows(data) # Writes all rows
# Reading from a CSV file
with open('people.csv', 'r') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
print(row) # Row is returned as a list
