Python File Handling: The Complete Beginner's Guide
This chapter teaches persistent data workflows: safe file reads/writes, modes, CSV and JSON, robust error handling, binary operations, and modern path work using pathlib.
Chapter 14 of 20 · Intermediate · 45 min · Python Programming Course
Every program you have written so far forgets everything when it stops. File handling gives your programs permanent memory.
What You Will Learn in This Chapter
By the end of this tutorial you will be able to:
- Open files safely with
with open() - Read files using
read(),readline(),readlines(), and iteration - Write and append content correctly
- Understand file modes and their risks
- Work with CSV and JSON files
- Handle paths safely with
pathlib - Handle file errors robustly
- Work with binary files
- Avoid common file handling mistakes
Estimated time: 45 minutes reading + 25 minutes practice
The open() Function
file = open("example.txt", "r")
content = file.read()
file.close()
This works, but can leak resources if an exception occurs before close().
Always Use with
with open("example.txt", "r") as file:
content = file.read()
The file closes automatically, even on errors.
File Modes
| Mode | Name | Behavior |
|---|---|---|
| `r` | Read | File must exist |
| `w` | Write | Truncates existing file |
| `a` | Append | Writes at end, preserves content |
| `x` | Exclusive create | Fails if file exists |
| `b` | Binary | Use with other modes (`rb`, `wb`) |
| `+` | Read+Write | Combined read/write modes |
Reading Files
read()
with open("poem.txt", "r") as file:
content = file.read()
readline()
with open("data.txt", "r") as file:
first_line = file.readline()
readlines()
with open("students.txt", "r") as file:
lines = file.readlines()
Iteration (recommended default)
with open("students.txt", "r") as file:
for line in file:
print(line.strip())
Writing and Appending
with open("output.txt", "w") as file:
file.write("First line\n")
file.write("Second line\n")
with open("log.txt", "a") as file:
file.write("New log entry\n")
Working With CSV
import csv
with open("students.csv", "r", newline="") as file:
reader = csv.DictReader(file)
for row in reader:
print(row["name"], row["score"])
import csv
rows = [{"name": "Alice", "score": 88}, {"name": "Bob", "score": 75}]
with open("output.csv", "w", newline="") as file:
writer = csv.DictWriter(file, fieldnames=["name", "score"])
writer.writeheader()
writer.writerows(rows)
Working With JSON
import json
data = {"course": "Python", "students": [{"name": "Alice", "score": 88}]}
with open("course_data.json", "w") as file:
json.dump(data, file, indent=2)
with open("course_data.json", "r") as file:
loaded = json.load(file)
pathlib - Modern Path Handling
from pathlib import Path
path = Path("data") / "processed" / "output.csv"
print(path.exists())
from pathlib import Path
p = Path("notes.txt")
p.write_text("Hello\n")
print(p.read_text())
Handling File Errors
try:
with open("missing.txt", "r") as file:
content = file.read()
except FileNotFoundError:
print("File not found")
except PermissionError:
print("Permission denied")
except IsADirectoryError:
print("Path is a directory")
Binary Files
with open("original.jpg", "rb") as source:
image_data = source.read()
with open("copy.jpg", "wb") as dest:
dest.write(image_data)
A Complete Working Program
CSV in, analysis, CSV+JSON out:
import csv
import json
from datetime import datetime
def read_student_scores(filepath):
students = []
with open(filepath, "r", newline="") as file:
reader = csv.DictReader(file)
for row in reader:
students.append({
"name": row["name"].strip(),
"scores": [int(x) for x in row["scores"].split("|")],
"course": row.get("course", "General"),
})
return students
def analyse_students(students):
results = []
for s in students:
avg = sum(s["scores"]) / len(s["scores"])
grade = "A" if avg >= 90 else "B" if avg >= 80 else "C" if avg >= 70 else "D" if avg >= 60 else "F"
results.append({
"name": s["name"],
"course": s["course"],
"average": round(avg, 1),
"grade": grade,
"passed": avg >= 60,
})
return sorted(results, key=lambda x: x["average"], reverse=True)
5 File Handling Mistakes Every Beginner Makes
- Opening files without
withand leaking handles - Using
wwhen you meanta - Forgetting to strip trailing newlines from lines
- Hardcoding path separators instead of
pathlib - Reading huge files entirely into memory unnecessarily
Practice Exercises
- Basic read/write with line numbers and word count
- CSV inventory value calculator
- JSON config loader/updater/reset
- Log analyzer for INFO/WARNING/ERROR
- Recursive file search utility with pathlib
-> See all Python File Handling exercises with solutions
What Comes Next - Day 15: Exception Handling
Day 15 dives deeper into robust error control:
try/except/else/finally- specific vs broad exceptions
- raising exceptions
- custom exception classes
- exception chaining
- exceptions vs return-value signaling
-> Continue to Day 15: Exception Handling
Frequently Asked Questions
What is file handling in Python?
Reading and writing persistent data on disk through file objects.
Why use with for file handling?
It guarantees file closure and prevents leaked resources.
Difference between r, w, and a modes?
r reads existing files, w overwrites, a appends.
Difference between read, readline, readlines?
Entire text, single line, or list of all lines respectively.
How do I work with CSV in Python?
Use the csv module, preferably DictReader/DictWriter.
How do I work with JSON in Python?
Use json.load/json.dump for files and loads/dumps for strings.
Why use pathlib?
Cleaner, cross-platform path operations with object-oriented API.
How do I handle file errors?
Catch specific exceptions like FileNotFoundError, PermissionError, and IsADirectoryError.
Chapter navigation
- Previous: Day 13: Modules and Packages
- Next: Day 15: Exception Handling
- Python Quiz: Take the Python quiz
- All Python exercises: Explore Python exercises
Frequently asked questions: File handling
What is file handling in Python?
File handling means reading from and writing to files so data persists beyond program execution.
What is the with statement in Python file handling?
with open(...) automatically closes files and is the recommended safe pattern.
What is the difference between 'r', 'w', and 'a' modes?
'r' reads existing files, 'w' overwrites or creates, and 'a' appends while preserving content.
What is the difference between read(), readline(), and readlines()?
read() returns full content, readline() returns one line, readlines() returns a list of lines.
How do I read a CSV file in Python?
Use csv.DictReader for header-based row access and open files with newline="" for compatibility.
How do I read and write JSON files in Python?
Use json.load/json.dump for files and json.loads/json.dumps for strings.
What is pathlib and why should I use it?
pathlib provides modern, readable, cross-platform path handling with Path objects.
How do I handle file errors in Python?
Catch specific exceptions like FileNotFoundError, PermissionError, and IsADirectoryError.
Related Page
Day 13: Modules and Packages
Learn about day 13: modules and packages
Learn MoreDay 15: Exception Handling
Continue with day 15: exception handling
Learn MorePython exercises hub
165+ programs with solutions
Learn MorePython quiz
Multiple-choice checks with explanations
Learn MorePython file handling programs
File operations, CSV, and JSON practice programs
Learn More