Read the whole file at once
with open("notes.txt") as f:
text = f.read()
print(text)
Read line by line (best for large files)
with open("notes.txt") as f:
for line in f:
print(line.strip())
Looping over the file reads one line at a time, so even a huge file uses very little memory. strip() removes the trailing newline.
Read every line into a list
with open("notes.txt") as f:
lines = f.readlines()
Handle a missing file gracefully
try:
with open("notes.txt") as f:
text = f.read()
except FileNotFoundError:
print("That file does not exist.")
Frequently asked questions
Why use with instead of open() on its own?
The with block closes the file automatically when you are done, so you never leak an open file handle — even if your code raises an error midway.
How do I read a file in another folder?
Pass a path: open("data/notes.txt") for a relative path, or a full path like open("/Users/me/notes.txt").
Learn file handling and more in our free Python course.