Site Tools


import-pathlib

import pathlib

import pathlib is a Python import that provides object-oriented filesystem paths. Prefer pathlib.Path over os.path for modern code; it's more readable and handles cross-platform paths automatically.

Example

# Python
# description: create paths, check existence, read files
 
from pathlib import Path
 
# Create a path object
p = Path("data/config.txt")
 
# Check if file exists
if p.exists():
    print(f"File exists at {p.resolve()}")
 
# Get file properties
print(f"Size: {p.stat().st_size} bytes")
 
# Read file contents
content = p.read_text()
 
# Write to file
output = Path("output.txt")
output.write_text("Hello, World!")
 
# Iterate over files in directory
for file in Path(".").glob("*.py"):
    print(file.name)

Common methods

  • Path(path): create path object
  • p.exists(): check if path exists
  • p.is_file(): check if it's a file
  • p.is_dir(): check if it's a directory
  • p.resolve(): get absolute path
  • p.name: filename with extension
  • p.stem: filename without extension
  • p.suffix: file extension
  • p.parent: parent directory
  • p.read_text(): read file as string
  • p.write_text(text): write string to file
  • p.mkdir(parents=True): create directory
  • p.glob(pattern): find files matching pattern
  • p.iterdir(): iterate over directory contents
import-pathlib.md · Last modified: by 127.0.0.1