On this page
File Handling in Python
Reading from Files
Python provides built-in functions to read from files. The most common way is using the open() function, followed by reading the file’s content.
- Opening a File:
file = open('filename.txt', 'r') # 'r' for read mode
- Reading the Entire File:
content = file.read()
print(content)
file.close() # Always close the file after reading
- Reading Line by Line:
with open('filename.txt', 'r') as file:
for line in file:
print(line.strip()) # .strip() removes extra whitespace
Using with open is recommended because it automatically handles file closing.
Writing to Files
You can write data to files using the write() or writelines() methods.
- Opening a File for Writing:
file = open('filename.txt', 'w') # 'w' for write mode, 'a' for append
- Writing a Single Line:
file.write("Hello, World!\n")
file.close()
- Writing Multiple Lines:
with open('filename.txt', 'w') as file:
lines = ["First line\n", "Second line\n", "Third line\n"]
file.writelines(lines)
Working with Different File Formats
Python provides specialized modules for working with various file formats like CSV and JSON.
- CSV Files:
import csv
# Reading CSV
with open('data.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
# Writing CSV
with open('output.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Name', 'Age', 'City'])
writer.writerow(['Alice', 30, 'New York'])
- JSON Files:
import json
# Reading JSON
with open('data.json', 'r') as file:
data = json.load(file)
print(data)
# Writing JSON
with open('output.json', 'w') as file:
json.dump({'name': 'Alice', 'age': 30, 'city': 'New York'}, file, indent=4)
Let me know if you need more examples or explanations on any of these topics!
File Modes Reference
| Mode | Description |
|---|---|
r |
Read (default) |
w |
Write (truncates existing) |
a |
Append |
r+ |
Read and write |
rb / wb |
Binary read/write |
pathlib — Modern Path API
from pathlib import Path
data_dir = Path('data')
data_dir.mkdir(exist_ok=True)
for csv_file in data_dir.glob('*.csv'):
print(csv_file.read_text(encoding='utf-8')[:100])
output = Path('output') / 'result.json'
output.write_text('{"status": "ok"}', encoding='utf-8')
Prefer pathlib over string concatenation for cross-platform paths.
Context Manager for Files
The with statement guarantees the file closes even if an exception occurs:
with open('log.txt', 'a') as f:
f.write('New entry\n')
# file automatically closed here
Reading Large Files Line by Line
with open('huge.log', 'r') as f:
for line in f:
if 'ERROR' in line:
print(line.strip())
This uses constant memory regardless of file size.
Handling Encoding Errors
with open('file.txt', 'r', encoding='utf-8', errors='replace') as f:
content = f.read()
Specify encoding='utf-8' explicitly — never rely on platform defaults.