Skip to lesson content

PYTHON / LESSON 11 OF 18

File handling

Read the explanations, work through the examples, and complete the student tasks.

Learning goals

Read and write text, append safely in a practice folder, and exchange structured CSV and JSON data.

Explanation

open creates a file object. Mode r reads an existing file, w creates or overwrites, a appends, x creates only if absent, and b selects binary mode. Use with so the file closes even when the block raises an exception. Specify encoding="utf-8" for text. Relative paths are resolved from the working directory, which may differ from the script's directory.

read loads the remaining contents; readline reads one line; readlines produces a list of lines. Iterating the file processes one line at a time and is useful for large inputs.

Example 1 Write append and read

This example creates or replaces practice_notes.txt in the current folder.

from pathlib import Path

path = Path("practice_notes.txt")
with path.open("w", encoding="utf-8") as file:
    file.write("Learn Python\n")
with path.open("a", encoding="utf-8") as file:
    file.write("Practice every day\n")
with path.open("r", encoding="utf-8") as file:
    for line_number, line in enumerate(file, start=1):
        print(line_number, line.rstrip("\n"))

Expected output:

1 Learn Python
2 Practice every day

The initial w resets the demo file on each run. The following a adds a second line. rstrip removes only the newline in this example.

Example 2 CSV and JSON round trip

This example creates or replaces students.csv and students.json.

import csv
import json

students = [{"name": "Ali", "score": 85},
            {"name": "Sara", "score": 92}]
with open("students.csv", "w", newline="",
          encoding="utf-8") as file:
    writer = csv.DictWriter(file, fieldnames=["name", "score"])
    writer.writeheader()
    writer.writerows(students)

with open("students.csv", newline="", encoding="utf-8") as file:
    rows = list(csv.DictReader(file))
print(rows[0]["name"], int(rows[0]["score"]))

with open("students.json", "w", encoding="utf-8") as file:
    json.dump(students, file, indent=2)
with open("students.json", encoding="utf-8") as file:
    restored = json.load(file)
print(restored[1]["name"], restored[1]["score"])

Expected output: Ali 85 and Sara 92. CSV reading returns textual fields, so convert the score when needed. JSON preserves basic numeric types. newline="" lets the csv module manage line endings correctly.

Common mistakes

Do not use w to read a valuable existing file: it truncates it. Do not parse general CSV by splitting at commas because quoted fields can contain commas. json.load reads a file, while json.loads reads a JSON string.

Student tasks

1. Write three goals to goals.txt, append one more, and print all four with line numbers.

2. Create a CSV with three students and calculate the average after reading it back. Scores 60, 75, and 90 must average 75.

3. Save a settings dictionary as JSON and read it back. Verify the restored dictionary equals the original.

Completion check: use with for every open file and submit both scripts and their generated practice data.