guideintermediate15 min
Reading and Writing Files
Load data from files and save your program's output. Work with text and CSV files.
Prerequisites
Last updated: Jan 28, 2026
Most programs need to read data from files or save results. Python makes file handling straightforward.
Reading Text Files
python
# The "with" statement ensures the file is properly closed
with open("example.txt", "r") as file:
content = file.read()
print(content)
# Read line by line
with open("example.txt", "r") as file:
for line in file:
print(line.strip()) # strip() removes the newline
# Read all lines into a list
with open("example.txt", "r") as file:
lines = file.readlines()
print(lines) # ['Line 1\n', 'Line 2\n', ...]Writing Text Files
python
# Write to a file (creates new or overwrites)
with open("output.txt", "w") as file:
file.write("Hello, World!\n")
file.write("This is line 2\n")
# Append to existing file
with open("output.txt", "a") as file:
file.write("This line is appended\n")
# Write multiple lines
lines = ["Line 1", "Line 2", "Line 3"]
with open("output.txt", "w") as file:
for line in lines:
file.write(line + "\n")
# Or use writelines (doesn't add newlines automatically)
with open("output.txt", "w") as file:
file.writelines(line + "\n" for line in lines)File Modes
python
# "r" - Read (default). Error if file doesn't exist
# "w" - Write. Creates new file or overwrites existing
# "a" - Append. Creates new file or adds to existing
# "x" - Create. Error if file already exists
# "r+" - Read and write
# For binary files (images, etc.), add "b"
# "rb", "wb", "ab"Working with CSV Files
CSV (Comma-Separated Values) is a common format for spreadsheet data:
python
import csv
# Reading CSV
with open("data.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row) # Each row is a list
# Reading CSV as dictionaries (using header row as keys)
with open("data.csv", "r") as file:
reader = csv.DictReader(file)
for row in reader:
print(row["name"], row["age"])
# Writing CSV
data = [
["name", "age", "city"],
["Alice", "25", "New York"],
["Bob", "30", "Boston"]
]
with open("output.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerows(data)Handling Errors
python
# Check if file exists before reading
import os
if os.path.exists("data.txt"):
with open("data.txt", "r") as file:
content = file.read()
else:
print("File not found")
# Or use try/except
try:
with open("data.txt", "r") as file:
content = file.read()
except FileNotFoundError:
print("File not found")
except PermissionError:
print("Permission denied")Practical Example: Process a Log File
python
def count_errors(log_file):
"""Count error messages in a log file."""
error_count = 0
error_lines = []
with open(log_file, "r") as file:
for line_number, line in enumerate(file, 1):
if "ERROR" in line.upper():
error_count += 1
error_lines.append((line_number, line.strip()))
return error_count, error_lines
# Use it
count, errors = count_errors("app.log")
print(f"Found {count} errors")
for num, text in errors[:5]: # Show first 5
print(f" Line {num}: {text}")Practice
- Write a program that counts words in a text file
- Read a CSV file and calculate the average of a numeric column
- Create a simple note-taking program that saves notes to a file
- Write a program that finds and replaces text in a file
- Read a file of numbers (one per line) and calculate statistics