Files & data
Medium
Read a text file with pathlib
Open and read UTF-8 text using pathlib.Path — modern and portable.
How it works
pathlib.Path wraps file paths with a clean object API. Path.read_text(encoding='utf-8') reads the whole file.
Always specify encoding for text files to avoid platform-specific defaults.
For large files, iterate lines with open() instead of loading everything into memory.
from pathlib import Path
path = Path("notes.txt")
if path.is_file():
text = path.read_text(encoding="utf-8")
print(text[:200])
else:
print("File not found — create notes.txt to try this sample.")
Sponsored
Sponsored
Reserved space — layout preview until AdSense is connected