Python (Fall 2026) Module 12-2: Reading and Writing Files
Watch on YouTube →
Overview
Bill Moseley explains how Python file objects read text with `read()` and `readline()`, and how their pointer advances as content is consumed. He also demonstrates writing with modes such as `w`, `a`, and `x`, emphasizing that the chosen mode and file state affect whether data is replaced, appended, or read successfully.
Key takeaways
- `read()` without an argument returns the entire file as a string, while `read(n)` returns up to `n` characters, including spaces and line breaks.
- `readline()` reads one line at a time and advances the file object's pointer, so each call normally retrieves the next line.
- Python's `write()` method does not add line breaks automatically; include `\n` when appended text should begin on a new line.
- Opening mode determines how writes affect a file: `w` replaces or creates, `a` appends, and `x` creates only when the path is new.
- To switch from appending to reading, close the file and reopen it with a reading mode rather than attempting to read through the append-opened object.
Chapters
0:00
Python `read()` Reads Entire Files or a Character Count
- Opening `intro.txt` creates a file object, but retrieving its contents requires a read method.
- `fiIntro.read()` returns the whole file as a string; `fiIntro.read(30)` returns up to the first 30 characters.
- Spaces, tabs, and newline characters count toward the requested character total, and newlines preserve the file's displayed structure.
3:29
Python `readline()` Advances the File Pointer One Line at a Time
- `fiIntro.readline()` reads one line, and a subsequent call starts at the next line because the file object tracks its position with a pointer.
- Repeated `readline()` calls can process a text file line by line, with the pointer moving forward after each read.
- The file's current position and how it was opened affect what later read operations return.
6:42
Python Write Modes, Appending Text, and Reopening Files
- The examples distinguish `w` for replacing or creating a file, `a` for appending, and `x` for creating a file only if it does not already exist.
- `write()` adds exactly the supplied string; to start appended text on a new line, include a newline character such as `\n`.
- After opening a file for appending, close it and reopen it for reading before attempting to read its contents.
- Choosing the wrong mode or using a file in the wrong state can damage data or prevent the intended operation.
Summary, takeaways, and chapters were generated by AI from the video's transcript and may contain errors. The video belongs to its creator, Bill Moseley, Ph.D. - Computer Science Educator.