agyanadda@gmail.com

Python File Handling

Files and Exceptions 1 min read Updated Dec 4, 2026 Topic 21 of 32

Open with with

with open("notes.txt", "r", encoding="utf-8") as f: — the file closes automatically when the block ends, even after errors.

Modes

Mode Meaning
r read (default)
w write — erases the file first
a append to the end
x create; error if it exists
b binary, e.g. rb for images

Reading

f.read(), f.readline(), f.readlines(), or loop for line in f: (best for big files).

Writing

f.write("text\n") — add \n yourself. f.writelines(list).

Always pass encoding="utf-8" for text, especially on Windows.

CSV files

csv.reader, csv.writer, and the friendlier csv.DictReader / csv.DictWriter. Open CSV files with newline="".

pathlib

from pathlib import Path — Path("data") / "report.txt", .exists(), .read_text(), .write_text(), .mkdir(parents=True, exist_ok=True), .glob("*.csv").

Example

Example — Save and read a CSV of students Python
import csv
from pathlib import Path

folder = Path("data")
folder.mkdir(exist_ok=True)
file = folder / "students.csv"

students = [
    {"name": "Asha", "course": "BCA", "marks": 88},
    {"name": "Ravi", "course": "MCA", "marks": 64},
]

with open(file, "w", newline="", encoding="utf-8") as f:
    writer = csv.DictWriter(f, fieldnames=["name", "course", "marks"])
    writer.writeheader()
    writer.writerows(students)

with open(file, newline="", encoding="utf-8") as f:
    for row in csv.DictReader(f):
        print(f"{row['name']:<6} {row['course']:<4} {row['marks']}")

log = folder / "log.txt"
with open(log, "a", encoding="utf-8") as f:
    f.write("Report generated\n")
print(log.read_text(encoding="utf-8"))

Creates data/students.csv, prints each student on a line (Asha BCA 88, Ravi MCA 64), and appends a line to data/log.txt each time it runs.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which mode adds to the end of a file without erasing it?

Exercise 2 True / False

Using with open(...) closes the file automatically.

Exercise 3 Fill in the Blank

Read a CSV as dictionaries with csv.___Reader

Frequently Asked Questions

The file's encoding does not match. Open text files with encoding="utf-8". For files saved by Excel, encoding="utf-8-sig" removes the hidden BOM character.