pathlib is the modern way to work with filesystem paths instead of plain strings.
Creating a path
from pathlib import Path
# Current directory
cwd = Path.cwd()
# Home directory
home = Path.home()
# From a string
p = Path('/Users/dmitrii/projects/myapp')
p = Path('src/tasks/models.py')
# BASE_DIR in Django
BASE_DIR = Path(__file__).resolve().parent.parent
Navigating the filesystem
p = Path('/home/user/projects/myapp/src/models.py')
p.name # 'models.py'
p.stem # 'models'
p.suffix # '.py'
p.parent # /home/user/projects/myapp/src
p.parents[0] # /home/user/projects/myapp/src
p.parents[1] # /home/user/projects/myapp
# Joining paths
data = BASE_DIR / 'data' / 'output.csv'
Reading and writing
p = Path('data.txt')
# Reading
text = p.read_text(encoding='utf-8')
data = p.read_bytes()
# Writing
p.write_text('Hello, World!', encoding='utf-8')
p.write_bytes(b'\x00\x01')
Checks
p = Path('config.json')
p.exists() # does it exist?
p.is_file() # is it a file?
p.is_dir() # is it a directory?
p.is_absolute() # is it an absolute path?
Creating and removing
# Create a directory
Path('logs').mkdir(exist_ok=True)
Path('a/b/c').mkdir(parents=True, exist_ok=True)
# Delete a file
Path('temp.txt').unlink(missing_ok=True)
# Delete an empty directory
Path('empty_dir').rmdir()
Traversing a directory
# All files
for f in Path('src').iterdir():
print(f)
# By pattern
for py_file in Path('src').glob('**/*.py'):
print(py_file)
# All Python files recursively
list(Path('.').rglob('*.py'))
Conversion
p = Path('/home/user/file.txt')
str(p) # '/home/user/file.txt'
p.as_posix() # '/home/user/file.txt'
# With os.path
import os
os.path.exists(p) # Path works anywhere a string is expected
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!