The essentials
Quick reference
One focused task per row. Jump to the related section for complete, working examples.
| Use | Syntax | Examples |
|---|---|---|
| Create a path object | config = Path('config/settings.json') | View examples |
| Join path segments | report = base / 'reports' / 'daily.txt' | View examples |
| Inspect path components | path.name, path.stem, path.suffix, path.parent | View examples |
| Check existence | path.exists() | View examples |
| Check the path kind | path.is_file(), path.is_dir() | View examples |
| Resolve an absolute path | absolute = path.resolve() | View examples |
| Create parent directories | output.mkdir(parents=True, exist_ok=True) | View examples |
| List directory entries | for child in directory.iterdir(): print(child.name) | View examples |
| Match child paths | for path in directory.glob('*.json'): print(path) | View examples |
| Search recursively | for path in directory.rglob('*.py'): print(path) | View examples |
| Read text | text = path.read_text(encoding='utf-8') | View examples |
| Write text | path.write_text(text, encoding='utf-8') | View examples |
| Process lines lazily | with path.open(encoding='utf-8') as file: lines = list(file) | View examples |
| Read bytes | data = path.read_bytes() | View examples |
| Write bytes | path.write_bytes(data) | View examples |
| Load JSON | data = json.loads(path.read_text(encoding='utf-8')) | View examples |
| Write readable JSON | path.write_text(json.dumps(data, indent=2) + '\n', encoding='utf-8') | View examples |
| Use a temporary directory | with TemporaryDirectory() as directory: work = Path(directory) | View examples |
| Replace a file atomically | temporary.replace(destination) | View examples |
Use pathlib for path construction and inspection, and context managers for streams that must close reliably. State encodings explicitly, distinguish text from bytes, bound memory use for large inputs, and write valuable output through a temporary file before replacing its destination.
Step by step
Detailed examples
Construct paths without string concatenation
Path objects model filesystem paths but perform no I/O until a method requests it. The / operator joins segments using the host platform's rules. name, stem, suffix, suffixes, and parent expose lexical components; they do not prove a target exists. Avoid embedding a particular operating system's separator in portable code.
from pathlib import Path
base = Path('workspace')
report = base / 'reports' / 'daily.txt'
print(report)
print(report.name)
print(report.stem)
print(report.suffix)
print(report.parent) workspace/reports/daily.txt
daily.txt
daily
.txt
workspace/reportsInspect current filesystem state deliberately
exists, is_file, and is_dir query state that can change immediately afterward, so do not use them as a substitute for handling errors from the real operation. resolve returns an absolute normalized result and supports strict=True when a missing component must be an error. Be cautious with symlinks when enforcing security boundaries.
from pathlib import Path
path = Path('notes.txt')
path.write_text('ready\n', encoding='utf-8')
print(path.exists())
print(path.is_file())
print(path.is_dir())
print(path.resolve().name) True
True
False
notes.txtCreate and discover directory entries
mkdir with parents=True builds missing ancestors; exist_ok=True ignores only the already-existing-directory case. iterdir does not promise sorted output, so sort when presentation or reproducibility matters. glob and rglob can visit large trees and have pathlib-specific hidden-file and recursive behavior; narrow the starting directory and pattern.
from pathlib import Path
root = Path('project')
(root / 'data' / 'archive').mkdir(parents=True, exist_ok=True)
(root / 'data' / 'one.json').write_text('{}', encoding='utf-8')
(root / 'data' / 'archive' / 'two.json').write_text('{}', encoding='utf-8')
print([path.name for path in sorted((root / 'data').glob('*.json'))])
print([path.name for path in sorted(root.rglob('*.json'))]) ['one.json']
['two.json', 'one.json']State text encoding and close streams reliably
read_text and write_text are concise for bounded files and close automatically. write_text overwrites an existing file, so use it only when replacement is intended. For large inputs or incremental processing, open the path in a with statement and iterate the stream. Newline translation occurs in text mode according to the platform and open options.
from pathlib import Path
path = Path('people.txt')
path.write_text('Ada\nGrace\n', encoding='utf-8')
print(path.read_text(encoding='utf-8').strip())
with path.open(encoding='utf-8') as file:
lengths = [len(line.rstrip('\n')) for line in file]
print(lengths) Ada
Grace
[3, 5]Use bytes for non-text data
Binary mode performs no character encoding or newline translation. read_bytes and write_bytes are suitable for bounded payloads; open with rb or wb for chunked data. Do not decode arbitrary binary files as text, and do not pass encoding in binary mode. As with write_text, write_bytes truncates an existing destination.
from pathlib import Path
path = Path('packet.bin')
written = path.write_bytes(b'\x89DATA\x00')
print(written)
print(path.read_bytes().hex()) 6
894441544100Serialize JSON as UTF-8 text
json.loads and dumps operate on strings, while json.load and dump operate on file objects. JSON supports a defined set of data types rather than arbitrary Python objects. Use UTF-8, select indentation and key ordering only when they serve a consumer, and never append independent JSON documents to one file unless using a defined streaming format.
import json
from pathlib import Path
path = Path('settings.json')
data = {'theme': 'dark', 'items_per_page': 25}
path.write_text(json.dumps(data, indent=2) + '\n', encoding='utf-8')
loaded = json.loads(path.read_text(encoding='utf-8'))
print(loaded['theme'])
print(loaded['items_per_page']) dark
25Finish valuable output before replacement
TemporaryDirectory provides isolated scratch space with automatic cleanup. For durable replacement, write a temporary file in the destination directory, flush and optionally fsync when durability requirements demand it, then replace the destination; same-filesystem replacement prevents readers from observing a partially written file. Atomic visibility and crash durability are separate guarantees.
import json
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as directory:
root = Path(directory)
destination = root / 'config.json'
destination.write_text('{"version": 1}\n', encoding='utf-8')
temporary = root / 'config.json.tmp'
temporary.write_text(json.dumps({'version': 2}) + '\n', encoding='utf-8')
temporary.replace(destination)
print(destination.read_text(encoding='utf-8').strip()) {"version": 2}Local code tester
Try Python files and paths
Run pathlib and JSON operations in the playground's local virtual filesystem.
Press Run to load Python locally.
Sources and further reading
References
Authoritative documentation used to verify and expand this cheat sheet.
- Python Software Foundationpathlib — Object-oriented filesystem pathsdocs.python.org
- Python Software FoundationReading and Writing Filesdocs.python.org
- Python Software Foundationjson — JSON encoder and decoderdocs.python.org
- Python Software Foundationtempfile — Generate temporary files and directoriesdocs.python.org
Help us improve
Found a typo or missing example?
Tell us what would make this cheat sheet clearer, more complete, or more useful.



