How to read a text file
Read an entire file
A with statement closes the file even if an error occurs. Specify UTF-8 explicitly for predictable text handling.
with open("notes.txt", "r", encoding="utf-8") as file:
content = file.read()
print(content)
Read line by line
Iterating the file avoids loading everything into memory. Each line usually includes its trailing newline.
with open("notes.txt", encoding="utf-8") as file:
for number, line in enumerate(file, start=1):
print(number, line.rstrip())
Use a path relative to the script
A plain relative path starts from the process working directory, not necessarily the script directory. pathlib can anchor data beside the script.
from pathlib import Path
path = Path(__file__).parent / "notes.txt"
text = path.read_text(encoding="utf-8")
print(text)
Handle a missing file
Catch the specific FileNotFoundError when absence is expected. Do not hide unrelated errors with a broad empty except.
try:
with open("notes.txt", encoding="utf-8") as file:
print(file.read())
except FileNotFoundError:
print("Create notes.txt first.")