Some text some message..
Back 16.1 How to Work with File Paths in Python 25 Jun, 2025

1. File Path Basics

  • A file path is a string that describes the location of a file or folder on your computer.

  • Paths can be:

    • Absolute path: Full path from the root directory (e.g., C:/Users/Abhi/Documents/file.txt)

    • Relative path: Path relative to your current working directory (e.g., ./data/file.txt or ../file.txt)


2. Using os.path Module (Standard way)

Python’s os.path module helps handle paths in a portable way (Windows, Linux, macOS):

import os

# Join paths correctly (handles slashes for your OS)
path = os.path.join('folder', 'subfolder', 'file.txt')
print(path)  # On Windows: folder\subfolder\file.txt, on Linux/macOS: folder/subfolder/file.txt

# Get the absolute path
abs_path = os.path.abspath('file.txt')
print(abs_path)

# Check if path exists
if os.path.exists(path):
    print("Path exists!")

# Get directory name from path
dir_name = os.path.dirname(path)
print("Directory:", dir_name)

# Get file name from path
file_name = os.path.basename(path)
print("File:", file_name)

3. Using pathlib Module (Modern & Recommended)

Since Python 3.4+, pathlib is a powerful and easy-to-use library to work with paths as objects:

from pathlib import Path

# Create a Path object
path = Path('folder') / 'subfolder' / 'file.txt'
print(path)  # folder/subfolder/file.txt or folder\subfolder\file.txt (auto)

# Check if path exists
if path.exists():
    print("File exists!")

# Get absolute path
abs_path = path.resolve()
print(abs_path)

# Get parent directory
print("Parent:", path.parent)

# Get file name
print("File name:", path.name)

# Read file contents easily (if it's a file)
if path.is_file():
    content = path.read_text()
    print(content)

4. Getting Current Working Directory

To know your script's current folder, use:

import os

cwd = os.getcwd()
print("Current Working Directory:", cwd)

Or with pathlib:

from pathlib import Path

cwd = Path.cwd()
print("Current Working Directory:", cwd)

Summary

Task os.path Example pathlib Example
Join paths os.path.join('folder', 'file.txt') Path('folder') / 'file.txt'
Absolute path os.path.abspath('file.txt') Path('file.txt').resolve()
Check if exists os.path.exists(path) path.exists()
Get filename os.path.basename(path) path.name
Get directory os.path.dirname(path) path.parent