๐Ÿ“ Python

pathlib: Working with Paths in Python

P
Author
PyLand Team
๐Ÿ“…
Published
30.06.2026
โฑ๏ธ
Reading time
1 min
๐Ÿ‘๏ธ
Views
360
๐ŸŒฟ
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

๐Ÿ“

if __name__ == "__main__": the Python entry point

The if name == "main" guard defines a Python program's entry point: it distinguishes direct...

๐Ÿ“… 14.08.2026 ๐Ÿ‘๏ธ 43
๐Ÿ“

strip() and lower(): Preparing User Text ๐Ÿงน

A user may enter the correct word with extra spaces or different letter case. Python...

๐Ÿ“… 11.08.2026 ๐Ÿ‘๏ธ 49
๐Ÿ“

ord(), chr(), and Cyclic Letter Shifts in Python ๐Ÿ”

A string contains characters, but a computer stores every character as a numeric code. Python...

๐Ÿ“… 09.08.2026 ๐Ÿ‘๏ธ 88