Python 3.4+pathlibterm
pathlib
module
Filesystem paths as objects: joining with /, name and suffix, reading and writing a file in one line.
Syntax
from pathlib import Path
For new code pathlib is handier than os.path: a path is a Path object rather than a string, its parts are attributes (name, suffix, parent) and joining uses the / operator. PurePath computes paths without touching the disk, while Path also talks to the filesystem. Legacy APIs that need a string get str(path); most of the standard library accepts a Path directly.
Examples
from pathlib import Path
p = Path('notes') / 'todo.txt'
print(p.name, p.suffix, p.parent) # → todo.txt .txt notes
p.parent.mkdir(exist_ok=True)
p.write_text('buy milk', encoding='utf-8')
print(p.read_text(encoding='utf-8')) # → buy milk
See also
Open in the full glossarydocs.python.orgReport an inaccuracy