The essentials

Quick reference

One focused task per row. Jump to the related section for complete, working examples.

UseSyntaxExamples
Create a path objectconfig = Path('config/settings.json')View examples
Join path segmentsreport = base / 'reports' / 'daily.txt'View examples
Inspect path componentspath.name, path.stem, path.suffix, path.parentView examples
Check existencepath.exists()View examples
Check the path kindpath.is_file(), path.is_dir()View examples
Resolve an absolute pathabsolute = path.resolve()View examples
Create parent directoriesoutput.mkdir(parents=True, exist_ok=True)View examples
List directory entriesfor child in directory.iterdir(): print(child.name)View examples
Match child pathsfor path in directory.glob('*.json'): print(path)View examples
Search recursivelyfor path in directory.rglob('*.py'): print(path)View examples
Read texttext = path.read_text(encoding='utf-8')View examples
Write textpath.write_text(text, encoding='utf-8')View examples
Process lines lazilywith path.open(encoding='utf-8') as file: lines = list(file)View examples
Read bytesdata = path.read_bytes()View examples
Write bytespath.write_bytes(data)View examples
Load JSONdata = json.loads(path.read_text(encoding='utf-8'))View examples
Write readable JSONpath.write_text(json.dumps(data, indent=2) + '\n', encoding='utf-8')View examples
Use a temporary directorywith TemporaryDirectory() as directory: work = Path(directory)View examples
Replace a file atomicallytemporary.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

01

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.

Build and inspect a report path
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)
Output
workspace/reports/daily.txt
daily.txt
daily
.txt
workspace/reports
Back to quick reference ↑
02

Inspect 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.

Resolve and classify a created path
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)
Output
True
True
False
notes.txt
Back to quick reference ↑
03

Create 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.

Create and find JSON documents
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'))])
Output
['one.json']
['two.json', 'one.json']
Back to quick reference ↑
04

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.

Write, read, and stream UTF-8 text
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)
Output
Ada
Grace
[3, 5]
Back to quick reference ↑
05

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.

Round-trip a binary header
from pathlib import Path

path = Path('packet.bin')
written = path.write_bytes(b'\x89DATA\x00')
print(written)
print(path.read_bytes().hex())
Output
6
894441544100
Back to quick reference ↑
06

Serialize 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.

Write and read a JSON configuration
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'])
Output
dark
25
Back to quick reference ↑
07

Finish 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.

Replace a configuration after complete serialization
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())
Output
{"version": 2}
Back to quick reference ↑

Local code tester

Try Python files and paths

Run pathlib and JSON operations in the playground's local virtual filesystem.

Runs in your browser
Output
Press Run to load Python locally.

Sources and further reading

References

Authoritative documentation used to verify and expand this cheat sheet.

  1. Python Software Foundationpathlib — Object-oriented filesystem pathsdocs.python.org
  2. Python Software FoundationReading and Writing Filesdocs.python.org
  3. Python Software Foundationjson — JSON encoder and decoderdocs.python.org
  4. 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.

Share feedback