Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to extract a part of the file path (a directory) in Python?
In Python, we can extract specific parts of a file path using built-in modules such as os.path and pathlib. Extracting parts of file paths is commonly needed when working with file systems, data processing, or scripts that handle files dynamically.
Using os.path Module
The os.path module provides functions to manipulate files and directory paths. We can use this module to extract directory names, file names, and traverse up directory levels.
Basic Directory Extraction
The following example shows how to use os.path.dirname() to extract the parent directory from a file path −
import os
file_path = "/home/user/documents/sample.txt"
# Extract the directory containing the file
directory = os.path.dirname(file_path)
print("Parent directory:", directory)
# Extract just the filename
filename = os.path.basename(file_path)
print("Filename:", filename)
Parent directory: /home/user/documents Filename: sample.txt
Extract Specific Path Components
We can extract particular parts of the path by splitting it using os.sep −
import os
file_path = "/home/user/documents/sample.txt"
# Split the path into components
parts = file_path.split(os.sep)
print("Path parts:", parts)
# Access specific parts (index 0 is empty for absolute paths starting with /)
print("Root:", parts[1]) # home
print("User:", parts[2]) # user
print("Directory:", parts[3]) # documents
print("File:", parts[4]) # sample.txt
Path parts: ['', 'home', 'user', 'documents', 'sample.txt'] Root: home User: user Directory: documents File: sample.txt
Using pathlib Module (Python 3.4+)
The pathlib module provides an object-oriented interface for working with file system paths. It is more readable and Pythonic compared to os.path and is recommended for Python 3.4 and above.
Basic Directory Extraction
The following example shows how to use pathlib.Path to extract directory information −
from pathlib import Path
file_path = Path("/home/user/documents/sample.txt")
# Extract the parent directory
print("Parent directory:", file_path.parent)
# Extract the filename
print("Filename:", file_path.name)
# Extract filename without extension
print("Stem:", file_path.stem)
# Extract file extension
print("Extension:", file_path.suffix)
Parent directory: /home/user/documents Filename: sample.txt Stem: sample Extension: .txt
Extract Specific Path Components
We can access specific parts of the path using the parts attribute, which returns path components as a tuple −
from pathlib import Path
file_path = Path("/home/user/documents/sample.txt")
# Get all parts of the path
parts = file_path.parts
print("Path parts:", parts)
# Access specific parts
print("Root:", parts[1]) # home
print("User:", parts[2]) # user
print("Directory:", parts[3]) # documents
print("File:", parts[4]) # sample.txt
# Navigate up directory levels
print("Parent:", file_path.parent)
print("Grandparent:", file_path.parent.parent)
Path parts: ('/', 'home', 'user', 'documents', 'sample.txt')
Root: home
User: user
Directory: documents
File: sample.txt
Parent: /home/user/documents
Grandparent: /home/user
Comparison
| Feature | os.path | pathlib |
|---|---|---|
| Python Version | All versions | 3.4+ |
| Interface | Function-based | Object-oriented |
| Readability | Good | Excellent |
| Cross-platform | Yes | Yes |
Conclusion
Use pathlib for modern Python projects as it provides a cleaner, object-oriented interface. Use os.path when working with older Python versions or when you need specific legacy functionality.
