2 min read

Python Pathlib Module

The pathlib module offers classes representing filesystem paths with semantics appropriate for different operating systems. It provides an object-oriented interface to filesystem paths, replacing older modules like os.path.

Importing the Module

from pathlib import Path

Creating Paths

You can create a path object by passing a string to the Path constructor.

from pathlib import Path

# Current directory
p = Path('.')

# Specific path
p = Path('/usr/bin/python3')

# Windows path
win_p = Path('C:/Windows/System32')

Basic Operations

Joining Paths

Use the / operator to join path components.

p = Path('/home/user')
sub_p = p / 'documents' / 'file.txt'
print(sub_p)
# Output (Linux): /home/user/documents/file.txt
# Output (Windows): \home\user\documents\file.txt

Checking Existence

p = Path('example.txt')

if p.exists():
    print("Path exists")

if p.is_file():
    print("It is a file")

if p.is_dir():
    print("It is a directory")

Path Manipulation

You can easily access parts of the path.

p = Path('/home/user/archive.tar.gz')

print(p.name)   # archive.tar.gz
print(p.stem)   # archive.tar
print(p.suffix) # .gz
print(p.parent) # /home/user

Reading and Writing Files

pathlib provides convenience methods for reading and writing text or bytes.

p = Path('hello.txt')

# Write text
p.write_text('Hello World!')

# Read text
content = p.read_text()
print(content)

Iterating Directories

You can iterate over directory contents using iterdir().

p = Path('.')

for child in p.iterdir():
    print(child)

Globbing

Find files matching a pattern.

# Find all .py files
for py_file in p.glob('*.py'):
    print(py_file)

# Recursive glob
for py_file in p.rglob('*.py'):
    print(py_file)

Resolving Paths

To get the absolute path, use resolve().

p = Path('hello.txt')
print(p.resolve())

programming/python/python