Python 3.4+Files & I/Oterm
pathlib.Path
pathlib
An object-oriented API for filesystem paths. Cross-platform.
Syntax
from pathlib import Path
p = Path('/some/path')
The constructor never touches the filesystem — a Path for a nonexistent location is created just fine, and existence is a separate question for exists() or is_file(). When components are joined, an absolute component throws away everything to its left, which bites when that component comes from user input. Build paths with the / operator rather than string concatenation: the separator follows the host OS, and on Windows forward slashes in the input are still understood.
Examples
from pathlib import Path
# Пример работает во временной папке: '/tmp' есть не на всякой системе,
# а tempfile.mkdtemp() даёт её кроссплатформенно.
import os, tempfile
base = Path(tempfile.mkdtemp())
os.chdir(base)
print(base.exists(), base.is_dir(), base.is_file()) # → True True False
# Сборка пути оператором /
f = base / 'test' / 'file.txt'
print(f.name, f.stem, f.suffix) # → file.txt file .txt
print(f.parent.name) # → test
# Чтение и запись — без open() и without with
note = base / 'note.txt'
note.write_text('Hello from pathlib!', encoding='utf-8')
print(note.read_text(encoding='utf-8')) # → Hello from pathlib!
# mkdir
new_dir = base / 'new_dir'
new_dir.mkdir(exist_ok=True)
print(new_dir.exists()) # → True
# glob — поиск по маске
(base / 'a.txt').write_text('a', encoding='utf-8')
(base / 'b.log').write_text('b', encoding='utf-8')
print(sorted(p.name for p in base.glob('*.txt'))) # → ['a.txt', 'note.txt']
# iterdir — обход содержимого папки
print(sorted(p.name for p in base.iterdir())) # → ['a.txt', 'b.log', 'new_dir', 'note.txt']
# stat и размер
print(note.stat().st_size) # → 19
See also
Open in the full glossarydocs.python.orgReport an inaccuracy