Python Path.read_text
Open a small text note and read back its contents.
A simple example
Path.read_text
- Start with A file containing A
- Do this Read it as text
- Result "A"
Syntax
path.read_text(encoding="utf-8")
Run these examples in Python
Save one example at a time as lesson.py. Use Python 3.9 or later.
python3 lesson.pyRead a saved shopping note
A small application saves a human-readable note for the next time it opens. Choose the text encoding and read or write the file deliberately so the saved characters can be recovered as intended.
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as folder:
path = Path(folder) / "today.txt"
path.write_text("milk", encoding="utf-8")
print(path.read_text(encoding="utf-8"))
milk
The program saves milk, then reads the same four characters from its temporary file.
Prepare a gallery label
A curator stores a short UTF-8 caption beside an exhibit. Save the note and read it back before the desk closes. Which characters are recovered?
Prepare a studio handover
A stage manager saves a two-word instruction for the next shift. Save the note and read it back before the desk closes. Which characters are recovered?
What to watch for
Use an explicit text encoding for shared data. A large file is usually better read in smaller pieces.