Bytebook Compiler

Real Programs

File Handling

Read and write text files safely with open() and with, file modes, reading line by line, CSV and JSON files, and working with paths using pathlib.

3 min read5 runnable examples4-question quiz

Opening files with with

The with statement opens a file and closes it automatically, even if an error happens inside the block:

Python
with open("notes.txt", "w") as f:          # "w" creates or overwrites
    f.write("Line one\n")
    f.write("Line two\n")
    print("Line three", file=f)            # print can write to files too

with open("notes.txt") as f:               # default mode is "r" (read text)
    print(f.read())

with open("notes.txt", "a") as f:          # "a" appends
    f.write("Line four\n")

with open("notes.txt") as f:
    for number, line in enumerate(f, start=1):   # iterate line by line: memory-friendly
        print(number, line.rstrip("\n"))
Output
Line one
Line two
Line three

1 Line one
2 Line two
3 Line three
4 Line four
Mode Meaning
"r" read (default); error if the file does not exist
"w" write; erases an existing file
"a" append to the end
"x" create; error if the file already exists
"r+" read and write
"b" binary, combined with the others: "rb", "wb"

Reading methods

Python
with open("poem.txt", "w") as f:
    f.write("Roses are red\nViolets are blue\nPython is neat\nAnd so are you\n")

with open("poem.txt") as f:
    first = f.readline()                 # one line
    rest = f.readlines()                 # list of the remaining lines
print(repr(first))
print(rest)

with open("poem.txt") as f:
    text = f.read()
print(len(text.split()), "words,", text.count("\n"), "lines")
Output
'Roses are red\n'
['Violets are blue\n', 'Python is neat\n', 'And so are you\n']
13 words, 4 lines

CSV files

The csv module handles commas inside quoted fields and other edge cases:

Python
import csv

rows = [["roll", "name", "marks"], [101, "Asha", 88], [102, "Ravi", 93], [103, "Meera, K", 79]]
with open("marks.csv", "w", newline="") as f:
    csv.writer(f).writerows(rows)

with open("marks.csv", newline="") as f:
    reader = csv.DictReader(f)                    # each row becomes a dict
    records = list(reader)

for r in records:
    print(f"{r['roll']} {r['name']:10} {r['marks']}")
average = sum(int(r["marks"]) for r in records) / len(records)
print(f"Class average: {average:.2f}")
Output
101 Asha       88
102 Ravi       93
103 Meera, K   79
Class average: 86.67

JSON files

JSON maps naturally onto Python dicts and lists — the standard format for configuration and web APIs:

Python
import json

profile = {"name": "Asha", "skills": ["C", "Python"], "cgpa": 9.1, "placed": False}
with open("profile.json", "w") as f:
    json.dump(profile, f, indent=2)

with open("profile.json") as f:
    loaded = json.load(f)
print(loaded["skills"], loaded == profile)
print(json.dumps({"ok": True, "count": 3}))      # to a string
Output
['C', 'Python'] True
{"ok": true, "count": 3}

Paths with pathlib

Python
from pathlib import Path

folder = Path("reports")
folder.mkdir(exist_ok=True)
for term in ("sem1", "sem2"):
    (folder / f"{term}.txt").write_text(f"Results for {term}\n")

for p in sorted(folder.glob("*.txt")):
    print(p.name, p.suffix, p.stat().st_size, "bytes:", p.read_text().strip())
print(Path("reports/sem1.txt").exists(), Path("missing.txt").exists())
Output
sem1.txt .txt 17 bytes: Results for sem1
sem2.txt .txt 17 bytes: Results for sem2
True False

Test yourself

4 questions · pick an answer to check it instantly

  1. 1

    What is the main advantage of with open(...) as f:?

  2. 2

    Which mode adds to the end of an existing file?

  3. 3

    What does f.readlines() return?

  4. 4

    Which module converts between Python dicts and JSON text?