How do you use pathlib.Path for modern, object-oriented file path manipulation instead of os.path's string-based functions?
Short answer
pathlib.Path represents a filesystem path as an OBJECT with useful methods and operator overloading (like '/' for joining paths), providing a more readable, cross-platform alternative to os.path's string-concatenation-based functions.
Advertisement
AModel answer
pathlib.Path represents a filesystem path as an OBJECT with useful methods and operator overloading (like '/' for joining paths), providing a more readable, cross-platform alternative to os.path's string-concatenation-based functions.
from pathlib import Path
data_dir = Path("data")
file_path = data_dir / "input.txt" # '/' operator joins paths cleanly
print(file_path.exists()) # True/False
print(file_path.suffix) # '.txt'
print(file_path.read_text()) # reads the entire file as a string, no 'with' neededReal-world example
Building cross-platform file path manipulation code that works consistently on both Windows and Unix-like systems.
Likely follow-ups
- How does Path.read_text() internally handle opening and closing the file, compared to a manual 'with open()' block?
Related topics