📝 Python

pathlib: Working with Paths in Python

P
Author
Pyland
📅
Published
30.06.2026
⏱️
Reading time
1 min
👁️
Views
104
🌿
Level
Medium

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

Your reaction to the article

💬 Comments (0)

🔐 Sign in to leave a comment
🚪 Login
💭

No comments yet

Be the first to share your opinion about this article!

🔗 Similar

Similar articles

Continue learning with these materials

📝

Event Loop in Python: How asyncio Achieves "Paral…

Event loop is the heart of asyncio. It doesn't run code in parallel across multiple...

📅 30.06.2026 👁️ 123
📝

pytest-django: Testing Django

Охватываемые темы: Installation, @pytest.mark.djangodb, Fixtures, Testing views.

📅 30.06.2026 👁️ 132
📝

pip: Python Package Manager

Охватываемые темы: Installing packages, Upgrading and removing, requirements.txt, Virtual environment.

📅 30.06.2026 👁️ 120

Did you like the article?

Subscribe to our updates and receive new articles first. Grow with PyLand!