Every program in this unit so far has been ephemeral: its data lives only in memory for the duration of a single run, gone the moment the interpreter exits. Files are how a program saves results for later, and how it reads data — a CSV of historical prices, a text file of trade instructions — that was not typed in interactively. This note covers Python's file-handling basics: opening a file in the right mode, reading and writing text, and the reproducibility habits (documenting expected input, always closing files, choosing write vs. append deliberately) that keep file-based programs trustworthy.
Learning objectives. By the end of this note you should be able to:
- open a file for writing, reading, or appending, and correctly choose among the three modes for a given task;
- write to and read from a file using
.write, iterating a file object directly withfor line in file_handle, and explain why each line includes a trailing newline; - explain the difference between opening a file for writing (
'w', which overwrites) versus appending ('a', which preserves existing content), and predict the resulting file contents for a given sequence of operations; - state the reproducibility habits (closing files, documenting expected input format, fixing random seeds when data is generated) this vault expects of every file-touching program.
In this lesson
- Opening, writing, and closing a file
- Reading a file
- Write vs. append: a deliberate, not default, choice
- Reproducibility habits for file-touching programs
Before you start
The full lesson, with worked examples and exercise solutions, is for members.
Read the full lessonNew to SelfMadeQuant.com? See membership options or browse the Python for Quantitative Finance syllabus.