Learn with diagrams, code, systems and practical examples.
Files and Paths
Read and write files safely with clear resource handling.
Scripts often need configuration, logs, generated output, CSV data, or local documents.
Start with the idea
Use with open(...) to make file lifetime explicit. pathlib gives an object-oriented way to work with filesystem paths across platforms.
Small working example
Run this example first. Do not change several things at once; confirm the basic behavior, then experiment.
from pathlib import Path
path = Path("notes.txt")
path.write_text("hello", encoding="utf-8")
print(path.read_text(encoding="utf-8")) Use with open(...) to make file lifetime explicit. pathlib gives an object-oriented way to work with filesystem paths across platforms.
- Files are external resources.
- Use explicit encodings.
- Paths should be handled deliberately.
helloThe example is intentionally small. Focus on the chapter’s main idea before adding extra syntax or framework code.
Common beginner mistake
Assuming the current working directory is always the directory where the script lives.
Be explicit about path roots when location matters, especially in automation and deployment environments.
Quick recap
- Files are external resources.
- Use explicit encodings.
- Paths should be handled deliberately.
Try it yourself
These are deliberately small. If you can complete them without copying the example, you are ready to continue.
- Write three lines to a file.
- Read them back and count the lines.