Explain it simply
Explain it simply
Reading a file is like watching a film. The player keeps a marker of where you are (the position). read() watches straight through to the end, readline() watches a single scene, and a for loop watches scene after scene.
Once you reach the end there is nothing left to watch, so calling read() again gives an empty string "". For big files, watching one scene at a time is best, because you never have to hold the whole film in your head at once.
Problem → Why → Solution
The problem: a big log file eats all the memory
A developer writes this script to count ERROR lines. It works on a 100 KB test file. Run against the 6 GB log on the production server, the process swallows all available memory and dies. And when they call read() a second time to print the first ERROR line, nothing comes out.
with open("app.log", encoding="utf-8") as f:
text = f.read() # the whole 6 GB file as one string
errors = text.split("\n") # ...and a second copy as a list
print(sum("ERROR" in line for line in errors))
again = f.read() # returns "" - the position is at the end
print(again[:80])Why does this happen?
read() loads the entire file into memory as one string, and split() makes a second full copy as a list. Memory grows in step with the file size. The second read() returns "" because a file object has a position: the first read() already moved it to the end, so there is nothing left to read.
Core concept: four ways to read, one position
A file object opened in text mode offers four ways to read. All of them start at the current position and move it forward by however much they read. Which one you pick depends on the file's size and on what you need to do with the data.
| Method | Returns | Use it when |
|---|---|---|
| f.read() | All remaining content as one str | The file is small and needed whole |
| f.readline() | One line with its \n, or "" at the end | You need just a header line |
| f.readlines() | A list of lines, each with \n | You need a list and the file is small |
| for line in f: | One line per loop step | Large files and most everyday work |
for line in f: keeps only one line (plus a small buffer) in memory, so memory use is about the same whether the file is 6 GB or 6 KB. Every line arrives with its \n at the end, except possibly the very last line if the file does not end with a newline. So strip it with line.rstrip("\n") or line.strip() before comparing or printing.
An empty string is how you detect the end. If readline() returns "", the file is finished; if it returns "\n", that is just a blank line and there is more to read. To read from the beginning again, move the position back with f.seek(0) or open the file afresh. For large binary files, pass a size such as f.read(65536) and read chunk by chunk until you get an empty result back.
Reading in text mode also decodes bytes into characters, and that step can fail. If a single byte is not valid UTF-8, the read raises UnicodeDecodeError at that point even when the rest of the file is fine. When you only need the readable parts, for example while searching old logs, open the file with errors="replace" and each undecodable byte becomes the U+FFFD replacement character instead of stopping the program. Avoid it for data you must store accurately, because it silently changes the content.
- open() puts the cursor at the start
- Each read moves the cursor forward
- At the end, reads return ""
- seek(0) jumps back to the start
The read methods differ only in how far they move the cursor per call.
General pattern
with open(path, encoding="utf-8") as f:
for line in f: # streams: one line in memory at a time
process(line.rstrip("\n"))
with open(path, encoding="utf-8") as f:
header = f.readline() # just the first line
rest = f.read() # everything after it
text = path.read_text(encoding="utf-8") # small files onlyThe everyday choice is for line in f:, stripping the \n from each line. Calling readline() and then read() continues from wherever the first call stopped. path.read_text() is a shortcut for small files.
Example: three ways to read the same file
This example creates a three-line file in a temporary folder and reads it three different ways. repr() makes each \n visible, so you can see exactly which method keeps the newlines.
import tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "readme.txt"
path.write_text("First line.\nSecond line.\nThird line.\n", encoding="utf-8")
with open(path, encoding="utf-8") as f:
content = f.read() # the whole file as one string
print(repr(content))
with open(path, encoding="utf-8") as f:
first = f.readline() # one line, newline included
rest = f.readlines() # every remaining line, as a list
print(repr(first))
print(rest)
with open(path, encoding="utf-8") as f:
for number, line in enumerate(f, start=1): # one line at a time
print(number, line.rstrip("\n"))Code breakdown
- Line 6
path.write_text("First line.\nSecond line.\nThird line.\n", encoding="utf-8")This creates the file to read. On Windows, text mode stores each \n as \r\n on disk, but reading in text mode turns it back into \n, so the output is identical on every system.
- Line 9
content = f.read() # the whole file as one stringread() returns a single str with all three \n characters inside it. Thanks to repr(), the output shows the quotes and the \n escapes.
- Lines 13-14
rest = f.readlines() # every remaining line, as a listreadline() reads the first line and leaves the cursor at the start of the second, so readlines() only gets the remaining two lines. Notice that "First line." is missing from the list.
- Lines 19-20
for number, line in enumerate(f, start=1): # one line at a timeThe file object is itself an iterator, so the for loop takes one line per step. enumerate(..., start=1) numbers the lines from 1. Without rstrip("\n"), the line's own newline plus print()'s newline would leave a blank line between lines.
'First line.\nSecond line.\nThird line.\n'
'First line.\n'
['Second line.\n', 'Third line.\n']
1 First line.
2 Second line.
3 Third line.Read CSV with the csv module
line.split(",") breaks a quoted value like "Smith, John" into two pieces. The csv module understands the quoting rules. As the csv documentation advises, open the file with newline="" so the module can handle newlines inside quoted fields itself. DictReader uses the first line as column names and gives you each row as a dict.
import csv
import tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "people.csv"
path.write_text('name,city\nAye,Yangon\n"Smith, John",Mandalay\n', encoding="utf-8")
with open(path, newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
print(row["name"], "|", row["city"])In real projects
Where this shows up in real projects
Scripts that ops teams write every day stream log files to count ERROR lines, tally requests per IP address, or pick out slow requests. Combining for line in f: with collections.Counter lets one pass over a multi-gigabyte file produce a summary using very little memory.
Data-import features read a user's uploaded CSV with csv.DictReader and treat every row as untrusted input: they check for missing columns, text where a number belongs, and wrong encodings, then report errors together with the row number. Reading the file is only the first step toward trustworthy data; validation is where the real work happens.
Config files are read the same way. For JSON settings you hand the open file object straight to json.load(f), and for TOML you use tomllib, part of the standard library since Python 3.11, with a file opened in "rb" mode. The parser does the reading, so you never split lines yourself.
Common mistakes
Common mistakes
1. Comparing lines without stripping the \n
if line == "admin": is never True even though users.txt contains admin, because the line is really "admin\n". Write line.strip() == "admin" instead.
2. Looping over the same file object twice
The first for loop leaves the cursor at the end, so a second loop over the same object runs zero times without any error. Call f.seek(0) before looping again, or store the lines in a list if the file is small.
3. Calling read() or readlines() on a huge file
Both read() and readlines() pull the entire file into memory, which is risky when you do not control the file's size. Read logs, exports and anything else that can grow with for line in f:.
Best practices
Best practices
- Default to for line in f: whenever you do not control how big the file can get.
- Use standard library modules for CSV, JSON and TOML instead of parsing them by hand.
- Treat data read from a file as untrusted input and check its types and ranges.
- Include line numbers in error messages; enumerate(f, start=1) makes that easy.
Mini challenge
Mini challenge: summarize a log file
Write summarize_log(), which streams a log of "LEVEL message" lines in one pass, counts the lines for each level, and collects the ERROR messages.
- Read the file with for line in f:, never read() or readlines()
- Skip blank lines
- Count levels with collections.Counter
- Create the log file inside a temporary directory
import tempfile
from collections import Counter
from pathlib import Path
SAMPLE = (
"INFO server started\n"
"WARNING disk 85% full\n"
"ERROR payment timeout order=17\n"
"\n"
"INFO request /home\n"
"ERROR payment timeout order=21\n"
)
def summarize_log(path: Path) -> tuple[Counter[str], list[str]]:
"""Stream the log once: count lines per level and collect ERROR messages."""
# TODO: open the file with utf-8 and loop over it line by line
# TODO: strip each line, skip blank ones, split off the level
# TODO: count the level; keep the message when the level is ERROR
...
# TODO: write SAMPLE to app.log in a temporary directory, summarize it, print resultsExpected: The program prints: {'INFO': 2, 'WARNING': 1, 'ERROR': 2} ERROR: payment timeout order=17 ERROR: payment timeout order=21
Show hint
line.partition(" ") splits at the first space and returns (level, " ", message). A Counter lets you do counts[key] += 1 even for a key it has not seen yet.
Show solution
import tempfile
from collections import Counter
from pathlib import Path
SAMPLE = (
"INFO server started\n"
"WARNING disk 85% full\n"
"ERROR payment timeout order=17\n"
"\n"
"INFO request /home\n"
"ERROR payment timeout order=21\n"
)
def summarize_log(path: Path) -> tuple[Counter[str], list[str]]:
"""Return a level -> count Counter and the list of ERROR messages."""
levels: Counter[str] = Counter()
errors: list[str] = []
with open(path, encoding="utf-8") as f:
for raw_line in f:
line = raw_line.strip()
if not line:
continue # blank line
level, _, message = line.partition(" ")
levels[level] += 1
if level == "ERROR":
errors.append(message)
return levels, errors
with tempfile.TemporaryDirectory() as tmp:
log_path = Path(tmp) / "app.log"
log_path.write_text(SAMPLE, encoding="utf-8")
levels, errors = summarize_log(log_path)
print(dict(levels))
for message in errors:
print("ERROR:", message)Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- read() gives one str, readline() one line, readlines() a list, and for line in f: one line per step.
- Every read moves the cursor forward and the end gives ""; call f.seek(0) to start over.
- Lines keep their \n, so strip() before comparing.
- Stream big files with for line in f:, and read CSV with the csv module.
Python Documentation — Reading and Writing Files — Python Software Foundation