Python Reading Files
In this page:
Reading Entire File
f.read() loads an entire file's contents into one string in memory at once -- convenient for small files, but risky for very large ones since the whole thing has to fit in RAM before your program can even start processing it.
Example: Reading Entire File
with open("data.txt", "w") as f:
f.write("all content at once")
with open("data.txt", "r") as f:
print(f.read())
Reading Line by Line
Looping directly over a file object ('for line in f:') reads one line at a time without loading the whole file into memory first, making it the memory-efficient choice for processing logs or datasets that might be gigabytes in size.
Example: Reading Line by Line
with open("data.txt", "w") as f:
f.write("line1\nline2\n")
with open("data.txt", "r") as f:
for line in f:
print(line.strip())
Reading All Lines into a List
f.readlines() reads the entire file and returns it as a list of strings, one per line -- unlike the line-by-line loop, this does load everything into memory, but gives you the convenience of indexing into a specific line number afterward.
Example: Reading All Lines into a List
with open("data.txt", "w") as f:
f.write("a\nb\nc\n")
with open("data.txt", "r") as f:
lines = f.readlines()
print(lines)
Safe Reading of Missing Files
Attempting to open a path that doesn't exist raises FileNotFoundError, so production code typically wraps file-opening in a try/except block to show a clear error message rather than letting the program crash with a raw traceback.
Example: Safe Reading of Missing Files
try:
with open("missing.txt", "r") as f:
print(f.read())
except FileNotFoundError:
print("File not found")
Stripping Newline Characters
Lines read from a file retain their trailing '\n' newline character, which is why you'll often see line.strip() or line.rstrip('\n') applied immediately after reading, to clean the text up before further processing.
Example: Stripping Newline Characters
with open("data.txt", "w") as f:
f.write("hello\n")
with open("data.txt", "r") as f:
line = f.readline()
print(repr(line))
print(repr(line.strip()))
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: