Python pathlib Module

The pathlib module in Python provides classes to handle filesystem paths in an object-oriented manner. It offers a simple way to work with paths and directories, making path manipulations more intuitive and concise compared to using the traditional os and os.path modules.

Table of Contents

  1. Introduction
  2. Key Classes
    • Path
    • PurePath
    • PurePosixPath
    • PureWindowsPath
  3. Common Methods and Properties
    • Creating Paths
    • Accessing Parts of a Path
    • Manipulating Paths
    • File Operations
    • Directory Operations
  4. Examples
    • Basic Path Operations
    • File and Directory Manipulations
    • Traversing Directories
  5. Real-World Use Case
  6. Conclusion
  7. References

Introduction

The pathlib module provides an object-oriented approach to handling filesystem paths. This module provides classes representing filesystem paths with semantics appropriate for different operating systems. This helps in writing code that is both more readable and more reliable.

Key Classes

Path

A subclass of PurePath representing concrete filesystem paths. It provides methods for filesystem operations.

PurePath

The base class for all paths, representing system-agnostic paths.

PurePosixPath

A subclass of PurePath representing non-Windows filesystem paths.

PureWindowsPath

A subclass of PurePath representing Windows filesystem paths.

Common Methods and Properties

Creating Paths

from pathlib import Path

# Create a Path object
path = Path('/home/user/file.txt')

# Create a Path object using the current working directory
current_path = Path.cwd()

# Create a Path object using the home directory
home_path = Path.home()

Accessing Parts of a Path

path = Path('/home/user/file.txt')

print(path.parent)  # /home/user
print(path.name)  # file.txt
print(path.stem)  # file
print(path.suffix)  # .txt
print(path.parts)  # ('/', 'home', 'user', 'file.txt')

Manipulating Paths

path = Path('/home/user/file.txt')

# Join paths
new_path = path / 'another_directory' / 'another_file.txt'
print(new_path)  # /home/user/file.txt/another_directory/another_file.txt

# Change file name
new_file_path = path.with_name('new_file.txt')
print(new_file_path)  # /home/user/new_file.txt

# Change file extension
new_ext_path = path.with_suffix('.md')
print(new_ext_path)  # /home/user/file.md

File Operations

path = Path('file.txt')

# Check if file exists
print(path.exists())  # True or False

# Read text from file
if path.exists():
    content = path.read_text()
    print(content)

# Write text to file
path.write_text('Hello, World!')

# Read bytes from file
if path.exists():
    content_bytes = path.read_bytes()
    print(content_bytes)

# Write bytes to file
path.write_bytes(b'Hello, World!')

Directory Operations

path = Path('my_directory')

# Check if directory exists
print(path.exists())  # True or False

# Create a directory
path.mkdir(parents=True, exist_ok=True)

# List directory contents
for item in path.iterdir():
    print(item)

# Remove a file
file_path = path / 'file.txt'
if file_path.exists():
    file_path.unlink()

# Remove an empty directory
if path.exists():
    path.rmdir()

Examples

Basic Path Operations

from pathlib import Path

# Create a Path object
path = Path('/home/user/file.txt')

# Access parts of the path
print(f"Parent: {path.parent}")  # Parent: /home/user
print(f"Name: {path.name}")  # Name: file.txt
print(f"Stem: {path.stem}")  # Stem: file
print(f"Suffix: {path.suffix}")  # Suffix: .txt

# Manipulate the path
new_path = path.with_name('new_file.txt')
print(f"New Path: {new_path}")  # New Path: /home/user/new_file.txt

File and Directory Manipulations

from pathlib import Path

# Create a new directory
dir_path = Path('my_directory')
dir_path.mkdir(parents=True, exist_ok=True)

# Create a new file and write text to it
file_path = dir_path / 'file.txt'
file_path.write_text('Hello, Pathlib!')

# Read text from the file
print(file_path.read_text())  # Hello, Pathlib!

# List directory contents
for item in dir_path.iterdir():
    print(item)  # my_directory/file.txt

# Remove the file and directory
file_path.unlink()
dir_path.rmdir()

Traversing Directories

from pathlib import Path

# Traverse directories and list all .txt files
base_path = Path('.')
for path in base_path.rglob('*.txt'):
    print(path)

Real-World Use Case

Organizing Files by Extension

from pathlib import Path
import shutil

# Organize files in the current directory by their extension
base_path = Path('.')
for file_path in base_path.iterdir():
    if file_path.is_file():
        ext = file_path.suffix[1:]  # Remove the leading dot
        target_dir = base_path / ext
        target_dir.mkdir(exist_ok=True)
        shutil.move(str(file_path), str(target_dir / file_path.name))

Conclusion

The pathlib module in Python provides an intuitive and powerful way to work with filesystem paths. It simplifies many common tasks related to file and directory operations, making code more readable and maintainable.

References

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top