compare approaches one problem · three ways
Compare Approaches
The same problem solved different ways in Python, run on the same input, with what really differs and when to use each.
read() vs readlines() vs iterating the file
Count the weather rows that recorded any precipitation.
what differs
read() loads the whole file into one string; readlines() into a list of lines (each ending in \n); iterating the file object reads a buffer at a time and yields lines lazily.
at a glance
| approach | use it when |
|---|---|
| A · read().splitlines() | Small files you'll look at more than once. |
| B · readlines() | Rarely: it's read() plus a list, with the newlines kept. |
| C · for line in f | Large files or streams: memory stays flat because only one line is held at a time. |
Watch out: Lines from readlines() and iteration keep their \n, so compare stripped text. This quick split works because the file has no quoted commas; use csv for real CSV.
the outputs
Each approach runs on the same input.
concepts
file objectslazy iterationmemory
learn it
Read and write a text file · Lazy pipelines: generator expressions, islice and takewhile
related comparisons