python pathlib - ghdrako/doc_snipets GitHub Wiki

The pathlib module allows for an enhanced representation of filesystem paths using appropriate classes, primarily Path, which simplifies operations through a clear, object-oriented mechanism. pathlib handles different path syntaxes automatically across diverse operating systems, ensuring cross-platform compatibility without additional logic or string- manipulation overhead.

from pathlib import Path # Creating Path objects current_dir = Path(’.’)
home_dir = Path.home() 
print(f"Current Directory: {current_dir}")
print(f"Home Directory: {home_dir}")

Working with Directories

Navigating and Modifying Paths

Path objects intuitively handle path concatenation. Use the division operator (/) to join paths.

sub_dir = current_dir / ’sub_folder’ / ’data’ print(f"Sub Directory:{sub_dir}")

Utilize properties like name, parent, stem, and suffix to extract path segments efficiently:

file_path = Path(’documents/letter.txt’) 
print(f"Name:{file_path.name}") # Output: letter.txt 
print(f"Stem:{file_path.stem}") # Output: letter print(f"Suffix: {file_path.suffix}")
# Output: .txt 
print(f"Parent: {file_path.parent}") # Output: documents

Creating and Removing Directories

# Create a directory 
new_dir = Path(’new_directory’)
new_dir.mkdir(exist_ok=True) 
# Remove a directory 
if new_dir.exists() and new_dir.is_dir(): 
  new_dir.rmdir()

These methods further engender robust error-management processes, leveraging exist_ok to bypass errors from existing directories—a convenience for scripts operating in controlled paths.

Exploring Directory Contents

Directory traversal via the iterdir(), glob(), and rglob() methods

# Iterating over directory contents 
for p in current_dir.iterdir():
  print(p) 
# Using glob patterns 
for p in current_dir.glob(’*.txt’):
  print(p) 
# Recursive search 
for p in current_dir.rglob(’*.py’): 
  print(p)

Cross-Platform Advantages

# Windows example \
path_win = Path(’C:/Program Files/example’)
print(path_win.is_absolute()) 
# True 
# UNIX example 
path_unix = Path(’/usr/bin/bash’) 
print(path_unix.is_absolute()) 
# True

Working with Files

File Creation and Deletion

# Creating and writing to a file 
file = Path(’example.txt’)
file.write_text("Hello, Pathlib!") 
# Deleting a file 
file.unlink()

File Access and Reading

file_content = file.read_text() 
print(file_content)