Lesson · File I/O & Filesystem
Working With Text Files
55 min readWorking With Text Files
Text files combine stream I/O with character encoding and newline rules. Iteration is often the simplest and most memory-efficient way to process large text files.
Learning goals
- Read a whole file with
read(), one line withreadline(), and all lines withreadlines(), and say what each returns at end of file. - Explain why iterating a file object keeps memory proportional to the longest line rather than the file size.
- Predict when
int(line)works directly on a line read from a file and when a blank line makes it fail. - Describe how
encoding=decides which bytes decode to which characters and which exception a bad decode raises. - Explain what newline translation does to
\r\ninput when a file is read in text mode.
Mental model
The three forms consume the same stream and return the same kind of value (str), so they are alternatives rather than layers: choose by how much text must be in memory and who decides when to advance. The encoding and newline rules from the file's open call apply to all of them, which is why the same file can produce different strings under different settings.
Mental model
read it top to bottom
read() one str for the whole file; memory grows with file size readline() one line per call; memory bounded by one line for line in file readline() repeated; same bounded memory
Core idea
A text file is a byte sequence plus two decoding rules: a character encoding and a newline convention. The reading APIs differ mainly in memory: read() materializes the whole file, readline() and iteration hold one line, and iteration is just readline() in a loop. Choose the API by how much content the program needs in hand before deciding anything.
read
read() consumes the rest of the stream (or the next size characters when given an argument) and returns it as one string in text mode, '' at end of file. It advances the stream position, so a second call continues where the first stopped; holding the full result is what makes it memory-hungry on large files.
readline
readline() returns the next line from the stream, including its trailing newline, or '' once the stream is exhausted. Each call advances the position by exactly one line, so it fits loops that parse or filter as they go and lets the code decide when to ask for another line.
Iteration
Iterating a file object (for line in file) yields one line per round, newline included, and stops at end of file. It is the memory-efficient default for large text files because only the current line is held, and it continues from wherever earlier reads left the stream position.
write
write() accepts a str in text mode, sends it to the stream, and returns the number of characters written. It adds no line endings or separators of its own, and the data may sit in the buffer until flush() or close() runs, so a reader can trail behind a writer that has not flushed.
Encodings
An encoding maps bytes to characters, and text mode uses the one passed to open(..., encoding=...); if it is omitted, the platform locale decides, so the same code can decode differently on another machine. A sequence that is invalid in the chosen encoding raises UnicodeDecodeError on read and UnicodeEncodeError on write.
Newlines
Text mode translates line endings: on reading, \r\n and \r are normalized to \n, and on writing, \n becomes the platform's line separator unless newline= controls it. This is why iteration yields clean \n-terminated strings even for files created on another platform.
Streaming large files
Iterate over a text file or read fixed-size chunks rather than calling read() on the whole file when input size can be large. Streaming keeps memory proportional to working state rather than file size.
Walkthrough
- The first block opens
large.txtin"w"mode, and the loop writes five lines withfile.write(f"{i}\n");iis converted to its decimal digits, and the explicit\nprovides each line ending. - The second block opens the same path in
"r"mode andfor line in filepulls one line per round, so every pass receives a string such as"0\n"with the newline attached. int(line)accepts the trailing\nbecauseint()ignores surrounding whitespace, so five plain numbers print; a blank line would raiseValueErrorinstead, because no digits remain.- Predict before running: the five output lines, then what
file.read()would print instead of the loop.
Experiments to try
- Run the script, then open
large.txtand confirm the bytes areb"0\n1\n2\n3\n4\n"; explain why the newline characters exist only because the code wrote them. - Replace the read loop with
file.read()and print the result; decide which form you would ship for a file of one million lines and why. - Call
readline()twice and printrepr()of each result; then read past end of file and observe''. - After the write block, append one more line in
"a"mode and iterate the file again; count the lines and explain the difference from reopening with"w".
Common mistakes
- Splitting lines by hand with
text.split("\n"): CRLF files leave a\ron every line, and a trailing newline produces an extra empty element, so parsing depends on which platform wrote the file. - Calling
read()on a large file just to loop over lines: the whole content is materialized as onestr, so memory grows with file size when iteration would have held only one line. - Passing blank or partial lines straight to
int()orfloat():int("")andint("\n")raiseValueErrorbecause stripping whitespace leaves no digits, so line-based parsers must skip or validate empties. - Assuming decode success means valid data: text mode only guarantees that the bytes mapped to characters, so numbers and column counts still need validation.
Practice: Easy
- Create
numbers.txtwith the worked example's write loop, then read it three ways (read(), tworeadline()calls, and iteration) and record the exact value each returns, printed withrepr()so the\ncharacters are visible. - Change the write loop to
range(1000)and read the file back withsum(int(line) for line in file); state the expected total before running and check it. - Write a file containing
caféwith UTF-8, then read it withencoding="ascii"and record the exact exception; read it again with UTF-8 and confirm the character survives.
Practice: Medium
- Rewrite the read half to count lines with
enumerate, then compare withlen(file.readlines()); explain which version holds more memory and when the difference matters. - Build a file with a deliberately blank line between numbers, demonstrate the
ValueErrorfromint(line), then fix the loop by skipping blank lines and report which lines the fix drops. - Refactor a version of the script that uses
read().splitlines()into one that iterates and callsstrip(); compare behavior on a file whose final line has no trailing newline.
Practice: Hard
- Write
total(path)that streams a large numeric text file and never holds more than one line; define its behavior for blank and non-numeric lines, then test it on a generated 100,000-line file. - Design a small line-oriented format (one record per line, fields separated by
|) and aparse(text)function; test it against input with a missing field and a blank line, and document which failure each case triggers. - Write a file whose lines end with
\r\nusing binary mode, then read it in text mode and printrepr()of each line; explain where the\rcharacters went and whyreadline()returns''at end of file.
Lesson checklist
- I can pick between
read(),readline(), and iteration based on how much of the file must sit in memory. - I can explain how
encoding=and newline translation turn disk bytes intostrvalues. - I can predict what
readline()returns at end of file and why blank lines break naive conversion loops. - I can strip or keep line endings deliberately instead of letting
split("\n")decide.
Remember
Text-mode reading is a chain of small decisions: the encoding turns bytes into characters, newline translation normalizes line endings, and the reading API decides how much text is in memory at once. Iteration is `readline()` in a loop, so it scales to files that `read()` cannot hold, and both hand back strings with their `\n` intact, which the parsing code must account for.
Interview angles
What is the main purpose of **read**?+
read() consumes the rest of the stream and returns it as one str (or the next size characters when given an argument), and returns '' once the file is exhausted. Because everything lands in memory at once, size the call for what the program can hold.
What should you pay attention to when using **readline**?+
readline() returns one line including its trailing \n, or '' at end of file, and each call advances the stream position. Mixing it with iteration or read() continues from that shared position, which surprises code that expects a fresh start.
How does **Iteration** fit into this lesson?+
Iterating a file object yields one line per round and stops at end of file; it is the memory-efficient default for large text files because only the current line is held. Iteration repeats the readline() step internally, so it sees the same strings, newline included.
Why does `int(line)` work for `"4\n"` but raise `ValueError` for a blank line?+
int() ignores surrounding whitespace, so a number followed by \n parses fine; a blank line has no digits left after that whitespace is stripped, so the conversion fails. Skip or validate blank lines before converting.