Python File Paths and Directories
What Is a File Path in Python?
A file path tells Python where to find or save a file or folder on your operating system. You can use:
- Absolute Path - Full path from the root directory.
- Relative Path - Path relative to the current working directory.
Absolute vs Relative Path in Python
Absolute Path Example:
path = "/home/user/documents/file.txt"
Relative Path Example:
path = "documents/file.txt"
Use os.getcwd() to check your current working directory:
import os
print(os.getcwd())
Using os.path for Cross-Platform Paths
Join Paths
import os
path = os.path.join("folder", "subfolder", "file.txt")
print(path)
Output (cross-platform):
- Linux/macOS: folder/subfolder/file.txt
- Windows: folder\subfolder\file.txt
Get Absolute Path
print(os.path.abspath("file.txt"))
Get File or Directory Name
print(os.path.basename("/home/user/file.txt")) # file.txt
print(os.path.dirname("/home/user/file.txt")) # /home/user
Check File or Directory Exists
print(os.path.exists("file.txt")) # True
print(os.path.isdir("folder")) # True
print(os.path.isfile("file.txt")) # True
Modern Path Handling with pathlib
from pathlib import Path
# Create path object
p = Path("folder") / "file.txt"
# Absolute path
print(p.resolve())
# Check if file exists
print(p.exists())
# Get parts of the path
print(p.parent) # folder
print(p.name) # file.txt
Example: Reading a File Using Path
from pathlib import Path
file_path = Path("docs") / "notes.txt"
if file_path.exists():
with open(file_path, "r") as file:
print(file.read())
Create Directories with Python
from pathlib import Path
# Create a single folder
Path("data").mkdir(exist_ok=True)
# Create nested folders
Path("data/year/month").mkdir(parents=True, exist_ok=True)
Best Practices for File Paths
- Use pathlib.Path for modern and clean syntax.
- Avoid hardcoding paths - use os.path.join() or / operator with Path.
- Always check if a file or folder exists before reading/writing.