Lesson · Python for Beginners
Read and write text files
Files let a small program preserve information after it stops running.
What you will learn
- Create a Path
- Read and write UTF-8 text
- Use a context manager for safe cleanup
Choose the file location
A relative path is interpreted from the program's current working directory, which may differ from the directory containing the script. pathlib.Path makes paths easier to build and inspect. During learning, print or inspect the path when a file seems to be missing, rather than assuming the program saved it somewhere else.
Write with a context manager
The with statement opens a file and arranges for it to be closed when the block ends, including when an error occurs. write_text replaces the file's content by default, so use it only when replacement is intended. Choose an encoding such as UTF-8 to handle text consistently across systems.
Read back and verify
read_text returns the file's contents as a string. The example writes to a temporary directory so it does not alter a learner's real documents, then reads from the same path. Testing a write by reading it back verifies both the path and the data.
Treat paths as input
A program should not build a path from untrusted text and write anywhere without checking the result. This example uses a controlled temporary location. For a real application, decide which directory is allowed and handle missing files and permissions with a clear message.
Plan for the file not being there
Reading a missing path raises FileNotFoundError, and writing may fail because of permissions or a full disk. A complete program should catch only failures it can explain or recover from, and it should not replace important data without a deliberate choice. Keep the example's temporary directory so repeated practice does not alter personal files.
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as folder:
path = Path(folder) / 'notes.txt'
path.write_text('Review loops', encoding='utf-8')
print(path.read_text(encoding='utf-8'))
Expected output
Review loops
Practice exercise
In a temporary directory, write the text 'first draft' to a file and read it back.
Show a hint
Use TemporaryDirectory and the same Path for both operations.
Show one possible solution
Create a Path inside TemporaryDirectory, call write_text with UTF-8, then print read_text using that same path.
Quick check
A context manager handles cleanup even if an exception interrupts the block.