Sponsored Reserved space — layout preview until AdSense is connected

Read a text file with pathlib

Open and read UTF-8 text using pathlib.Path — modern and portable.

8 lines 2 views 0 copies Updated May 23, 2026
Try in editor

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.

Python
Try in editor
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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Files & data