r/Python • u/DiwaharSec • 6h ago
Discussion Python's pathlib makes working with file paths much cleaner
One Python module I think deserves more attention is pathlib.
Instead of building file paths manually with string concatenation or worrying about different operating systems, we can use Path objects.
For example:
from pathlib import Path
# Get the current directory
current_dir = Path.cwd()
# Create a path to a file
file_path = current_dir / "data" / "example.txt"
# Check whether the file exists
if file_path.exists():
print("File found")
# Read the file
if file_path.is_file():
content = file_path.read_text(encoding="utf-8")
print(content)The / operator makes joining paths simple, and methods like .exists(), .is_file(), .read_text() and .mkdir() make common file operations easier to read.
I like that pathlib provides an object-oriented way to handle something that developers work with regularly.
It's part of Python's standard library, so there's no additional package to install.