Part 08 / Topic 3 of 10
Reading: read(), readline(), looping
A file object remembers where it is, like a bookmark. Each read continues from where the last one stopped.
Real-world example: read a class list.
with open("demo_class.txt", "w", encoding="utf-8") as f:
f.write("Aarav\nPriya\nRohan\n")
with open("demo_class.txt", encoding="utf-8") as f:
print(repr(f.readline())) # 'Aarav\n' (one line, with its \n)
print(repr(f.read())) # 'Priya\nRohan\n' (the REST of the file)
with open("demo_class.txt", encoding="utf-8") as f:
for number, line in enumerate(f, start=1):
print(number, line.strip())
# 1 Aarav
# 2 Priya
# 3 Rohan
| Method | Returns | Use when |
|---|---|---|
f.read() |
Whole file as one str |
Small files |
f.readline() |
Next line ("" at the end) |
Read a header line first |
f.readlines() |
List of lines | Small files, need a list |
for line in f: |
One line at a time | โ Best for big files (low memory) |
Each line ends with "\n". Use line.strip() (or rstrip("\n")) to remove it.
๐ Going deeper: a file object is an iterator: it hands out one line at a time and is used up after one pass. That is why the loop above opens the file again.
f.seek(0)moves the bookmark back to the start instead.
Done here? The practice set for Part 8 โ 8 exercises with solutions โ is on the part page.