Python File Handling - Read, Write, Append Files Tutorial
Working with Files
Python makes file I/O straightforward with the built-in open() function. Always use the with statement - it automatically closes the file even if an error occurs.
File Modes
| Mode | Description |
|---|---|
'r' | Read (default) - error if file doesn't exist |
'w' | Write - creates file or overwrites existing |
'a' | Append - adds to end of file |
'x' | Create - error if file already exists |
'r+' | Read and write |
'b' | Binary mode (e.g., 'rb', 'wb') |
't' | Text mode (default) |
Reading Files
# Read entire file as a string
with open("data.txt", "r") as f:
content = f.read()
print(content)
# Read line by line (memory-efficient for large files)
with open("data.txt", "r") as f:
for line in f:
print(line.strip()) # strip() removes trailing newline
# Read all lines into a list
with open("data.txt", "r") as f:
lines = f.readlines()
print(lines) # ['line1\n', 'line2\n', ...]
# Read one line at a time
with open("data.txt", "r") as f:
first_line = f.readline()
second_line = f.readline()
# Specify encoding (important for non-ASCII text)
with open("data.txt", "r", encoding="utf-8") as f:
content = f.read()
Writing Files
# Write (overwrites existing content)
with open("output.txt", "w") as f:
f.write("Hello, World!\n")
f.write("Second line\n")
# Write multiple lines at once
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("output.txt", "w") as f:
f.writelines(lines)
# Append to existing file
with open("log.txt", "a") as f:
f.write("New log entry\n")
# Write with print() - convenient for formatted output
with open("report.txt", "w") as f:
print("Report Title", file=f)
print(f"Total: {42}", file=f)
Working with JSON Files
import json
# Write JSON to file
data = {
"name": "Alice",
"age": 25,
"hobbies": ["coding", "reading"]
}
with open("data.json", "w") as f:
json.dump(data, f, indent=2)
# Read JSON from file
with open("data.json", "r") as f:
loaded = json.load(f)
print(loaded["name"]) # Alice
print(loaded["hobbies"]) # ['coding', 'reading']
# Write list of records
users = [
{"id": 1, "name": "Alice"},
{"id": 2, "name": "Bob"},
]
with open("users.json", "w") as f:
json.dump(users, f, indent=2)
Working with CSV Files
import csv
# Write CSV
students = [
["Name", "Age", "Grade"],
["Alice", 20, "A"],
["Bob", 22, "B"],
["Charlie", 21, "A"],
]
with open("students.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(students)
# Read CSV
with open("students.csv", "r") as f:
reader = csv.reader(f)
for row in reader:
print(row)
# DictReader - rows as dicts
with open("students.csv", "r") as f:
reader = csv.DictReader(f)
for row in reader:
print(f"{row['Name']}: {row['Grade']}")
# DictWriter - write from dicts
with open("output.csv", "w", newline="") as f:
fieldnames = ["name", "score"]
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({"name": "Alice", "score": 95})
writer.writerow({"name": "Bob", "score": 87})
File System Operations with pathlib
from pathlib import Path
# Create path objects
p = Path("data/output.txt")
home = Path.home()
cwd = Path.cwd()
# Path operations
print(p.name) # output.txt
print(p.stem) # output
print(p.suffix) # .txt
print(p.parent) # data
# Check existence
print(p.exists())
print(p.is_file())
print(p.is_dir())
# Create directories
Path("new_folder/sub").mkdir(parents=True, exist_ok=True)
# Read and write (modern way)
p = Path("hello.txt")
p.write_text("Hello, World!")
content = p.read_text()
print(content)
# List files in directory
for f in Path(".").iterdir():
print(f)
# Find all Python files recursively
for py_file in Path(".").rglob("*.py"):
print(py_file)
# Delete file
p.unlink(missing_ok=True)
Level Up Your Python Skills
Master Python with these hand-picked resources
10,000+ learners
Free forever
Updated 2026
Related Python Topics