pythonbeginner

Python Pathlib File Operations

Modern file system operations using pathlib for cross-platform path handling and file management.

python
from pathlib import Path

# Path creation and navigation
cwd = Path.cwd()
home = Path.home()
config = home / ".config" / "myapp" / "settings.json"

# Path info
print(config.name)       # settings.json
print(config.stem)       # settings
print(config.suffix)     # .json
print(config.parent)     # ~/.config/myapp
print(config.parts)      # ('/', 'Users', ...)

# Create directories
output = Path("output/reports/2024")
output.mkdir(parents=True, exist_ok=True)

# Read and write files
path = Path("data.txt")
path.write_text("Hello, World!")
content = path.read_text()

# Binary files
binary_path = Path("image.bin")
binary_path.write_bytes(b"\x89PNG...")
data = binary_path.read_bytes()

# Glob patterns
for py_file in Path("src").rglob("*.py"):
    print(py_file)

# List directory contents
for item in Path(".").iterdir():
    kind = "DIR" if item.is_dir() else "FILE"
    print(f"[{kind}] {item.name}")

# Path checks
path = Path("somefile.txt")
path.exists()     # True/False
path.is_file()    # True/False
path.is_dir()     # True/False

# Rename / move
old = Path("old_name.txt")
old.rename("new_name.txt")

# Get file info
stats = Path("data.csv").stat()
print(f"Size: {stats.st_size} bytes")
print(f"Modified: {stats.st_mtime}")

# Resolve relative paths
absolute = Path("../project/src").resolve()
relative = Path("/a/b/c").relative_to("/a")

Use Cases

  • Cross-platform file path handling
  • Directory traversal and file discovery
  • Reading and writing files with clean API

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.