How do I work with file paths and directories in Python?
· Category: Python Programming
Short answer
Use pathlib.Path for modern, object-oriented path manipulation. For older code, os.path is still available. Both allow you to join paths, check existence, list directories, and create folders portably.
Steps
- Create a
Pathobject:from pathlib import Path. - Use
/to join paths. - Use methods like
.exists(),.mkdir(),.glob(), and.read_text().
from pathlib import Path
data_dir = Path("data")
data_dir.mkdir(parents=True, exist_ok=True)
file_path = data_dir / "input.txt"
if file_path.exists():
print(file_path.read_text(encoding="utf-8"))
# List files
for txt_file in data_dir.glob("*.txt"):
print(txt_file.name)
Tips
pathlibis preferred overos.pathfor new code because it is more readable and cross-platform.- Use
Path.home()andPath.cwd()to get the home directory and current working directory. os.walk()is still useful for recursive directory traversal with complex filtering.
# os.walk example
import os
for root, dirs, files in os.walk("."):
for name in files:
print(os.path.join(root, name))
Common issues
- Hardcoding backslashes (
\) breaks on Linux/macOS; always usepathliboros.path.join. mkdir()withoutexist_ok=TrueraisesFileExistsErrorif the directory already exists.- Relative paths depend on the current working directory, which may differ between IDE, terminal, and cron jobs.