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 get the file name from the file path in Python?
When working with file paths in Python, you often need to extract just the filename from a complete file path. Python provides several methods to accomplish this task using different modules.
Method 1: Using os.path.basename()
The most common and straightforward approach is using the os.path.basename() function, which returns the final component of a file path ?
import os
# Input file path
file_path = 'C:/Users/Documents/tutorial.pdf'
# Extract filename using os.path.basename()
filename = os.path.basename(file_path)
print("The filename is:", filename)
The filename is: tutorial.pdf
Method 2: Using os.path.split()
The split() function separates the directory path from the filename and returns both as a tuple ?
import os
file_path = 'C:/Users/Documents/tutorial.pdf'
# Split path into directory and filename
directory, filename = os.path.split(file_path)
print("Directory:", directory)
print("Filename:", filename)
Directory: C:/Users/Documents Filename: tutorial.pdf
Method 3: Using Pathlib Module
The modern pathlib module provides an object-oriented approach to handle file paths ?
from pathlib import Path
file_path = 'C:/Users/Documents/tutorial.pdf'
# Create Path object
path_obj = Path(file_path)
# Get filename with extension
print("Filename with extension:", path_obj.name)
# Get filename without extension
print("Filename without extension:", path_obj.stem)
# Get only the extension
print("Extension:", path_obj.suffix)
Filename with extension: tutorial.pdf Filename without extension: tutorial Extension: .pdf
Method 4: Using Regular Expressions
For pattern-based extraction, you can use regular expressions to match specific filename patterns ?
import re
file_path = 'C:/Users/Documents/tutorial.pdf'
# Pattern to match filename with extension
pattern = r'[^/\]*$'
filename = re.search(pattern, file_path).group()
print("Filename:", filename)
# Pattern to match filename without extension
pattern_no_ext = r'[^/\]*(?=\.)'
filename_no_ext = re.search(pattern_no_ext, file_path).group()
print("Filename without extension:", filename_no_ext)
Filename: tutorial.pdf Filename without extension: tutorial
Comparison
| Method | Module Required | Best For |
|---|---|---|
os.path.basename() |
os | Simple filename extraction |
pathlib.Path |
pathlib | Modern, object-oriented approach |
os.path.split() |
os | When you need both directory and filename |
| Regular expressions | re | Pattern-based extraction |
Conclusion
The os.path.basename() method is the most straightforward for basic filename extraction. Use pathlib for modern Python applications, and regular expressions for complex pattern matching requirements.
