Skip to main content

Python Tutorial 7.2 - File Path Handling

Welcome to the “File Path Handling” tutorial!


Overview

Use the os and pathlib modules for cross-platform path operations.

Using os.path

import os

# Build a path
path = os.path.join('folder', 'subfolder', 'file.txt')
print(os.getcwd())              # current working directory
print(os.path.exists(path))     # check existence

Using pathlib (Python 3.4+)

from pathlib import Path

p = Path('folder') / 'subfolder' / 'file.txt'
print(p.exists())               # check existence
print(p.read_text())            # read entire file

Creating Directories

os.makedirs('new_folder/sub', exist_ok=True)
# or with pathlib
Path('new_folder/sub').mkdir(parents=True, exist_ok=True)

Key Takeaways

  • os.path.join avoids hard-coding separators.
  • pathlib.Path offers an object-oriented API.
  • Use exist_ok=True to prevent errors when directories already exist.

Happy coding!

Comments