Python › File I/O & Context Managers
How do you use pathlib.Path for modern, object-oriented file path manipulation instead of os.path's string-based functions?
IntermediateAnswer
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.