Reading and Writing Files, Including CSV
Opening a file, reading it line by line or writing to it, and closing it again, plus the row-and-column shape of CSV. This is where a program's data starts outliving the run that produced it.
What a learner can do afterwards
- Read a text file line by line and build a result from it
- Write records to a CSV file and read them back into objects or dictionaries
- Say what closing a file does, and what a relative path depends on
1 · Read
open(path, mode) returns a file object. Mode 'r' reads an existing file; 'w' creates or truncates one; 'a' appends.
close() flushes buffered output and releases the resource. flush() can also flush output but leaves the file open. A with block closes its file on exit. Flushing does not by itself guarantee durable physical storage.
readline() reads the next line. Iterating over a text file also reads lines in order. This loop builds a total from scores.txt containing 7 and 2 on separate lines: ```python with open("scores.txt", "r") as f: total = 0 for line in f: total += int(line) ``` The total is 9. Each converted line is added to the running result.
A relative path such as data.txt is resolved against the process's current working directory, which can differ from the script's folder. An absolute path starts from a filesystem root. A subfolder path can still be relative. Saved data remains in the file after the run ends; a fresh run must read it into new variables.
CSV separates fields with commas. Quoting allows commas or line breaks inside a field, so a physical line need not be a record. csv.reader removes enclosing CSV quotes and returns strings: "Oak, red" becomes Oak, red. ```python import csv with open("books.csv", "w", newline="") as f: w = csv.DictWriter(f, fieldnames=["name", "pages"]) w.writeheader() w.writerow({"name": "Oak, red", "pages": 8}) ```
Read the saved records using their headers, then reconstruct numeric values: ```python with open("books.csv", "r", newline="") as f: records = list(csv.DictReader(f)) for row in records: row["pages"] = int(row["pages"]) ``` DictReader initially gives string values. int restores the page count's numeric type. Printing f itself shows file-object details, not its contents.
A text line may retain its final newline. If only that newline should be removed, line.rstrip('\n') removes trailing newline characters while preserving spaces. Unrestricted strip() also removes surrounding whitespace, which may be meaningful. Text-file write() does not add a newline automatically; include '\n' when the format needs one.
Choose the file mode, track the read position and close the resource. Resolve relative paths from the current working directory. Use CSV tools and reconstruct value types.
File-operation teaching adapted from the Introduction to Python Programming chapter 14 corpus records, with corrected path and buffering explanations and independently written CSV examples and assessments.
Rewritten readings were written for this dataset.
2 · Watch
Take it off screen
Where it sits
8 questions wait behind this lesson, each with its answer explained. Every answer feeds the sky: stars light as they are learned, and dim when it is time to come back.