
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Extract Part of the File Path in Python
In Python, we can extract a specific part of a file path of the directory using built-in modules such os.path and pathlib. Extracting a part of the file path is commonly needed when working with file systems, data processing, or scripts that handle files dynamically.
Using os.path Module
The os.path module in Python provides functions to manipulate files and directory paths. We can use this module to extract directory names, file names, and traverse up directory levels.
Example
Following is an example, which shows how to use the os.path module to extract a directory path from a full file path -
import os file_path = r"D:\Tutorialspoint\sample" # Extract the directory containing the file directory = os.path.dirname(file_path) print(directory)
Following is the output of the above program -
D:\Tutorialspoint
Extract a Specific Directory
We can also extract a particular part of the path by splitting it using os.sep. Following is an example of using the os.sep to extract a part of the file path -
import os file_path = r"D:\Tutorialspoint\sample" # Extract the directory containing the file directory = os.path.dirname(file_path) print(directory) parts = file_path.split(os.sep) # Example: Get the third part of the path print(parts[2]) # Output: Tutorials
Here is the output of the above example -
D:\Tutorialspoint sample
Using pathlib
Module (Python 3.4+)
The pathlib module in Python provides an object-oriented interface for working with file system paths. It is more readable and Pythonic compared to the older os.path module and is recommended for Python 3.4 and above.
Example
Following is an example, which shows how to use the pathlib module to extract a directory path from a full file path -
from pathlib import Path file_path = Path(r"D:\Tutorialspoint\sample") # Extract the parent directory print(file_path.parent)
Following is the output of the above program -
D:\Tutorialspoint
Extract a Specific Directory
We can access any specific part of the path using the parts attribute and which returns the path components as a tuple -
from pathlib import Path file_path = Path(r"D:\Tutorialspoint\sample") # Extract the parent directory print(file_path.parent) # Get the parts of the path parts = file_path.parts # Example: Get the third part of the path print(parts[2]) # Output: Tutorials
Here is the output of the above program -
D:\Tutorialspoint sample