Python extract file name from file path example 2025
Added 'extract' for clarity, included 'example' to find practical implementations, and added the year for up-to-date resources.
Extracting the file name from a file path in Python can be accomplished in several effective ways. This process is essential for numerous applications, such as file management, data processing, or simply displaying user-friendly file names in log outputs. In this guide, we will explore different methods available in Python for extracting the file name, ensuring compatibility across various operating systems.
os.path ModuleThe os.path module provides a simple way to retrieve the file name from a path using the basename function. This method is straightforward and works across different operating systems (Windows, macOS, Linux).
import os
file_path = "/path/to/your/file.txt"
file_name = os.path.basename(file_path)
print(file_name) # Output: file.txt
Explanation: The basename() function returns the last component of the path, which is the file name.
pathlib ModulePython’s pathlib module offers a more modern and object-oriented approach to handle filesystem paths. It provides the Path class, which can be utilized to extract the file name easily.
from pathlib import Path
file_path = Path("/path/to/your/file.txt")
file_name = file_path.name
print(file_name) # Output: file.txt
Explanation: The name property of a Path object gives the file name along with the extension.
While not as robust as the previous methods, string manipulation can still be used effectively to extract the file name from a path. This method involves splitting the path by the directory separators.
file_path = "/path/to/your/file.txt"
file_name = file_path.split("/")[-1] # For Linux
# Or for Windows
# file_name = file_path.split("\\")[-1]
print(file_name) # Output: file.txt
Explanation: This method uses string splitting to get the last element after the final directory separator.
If you need to extract just the file name without its extension, both os.path and pathlib offer handy functions.
os.pathimport os
file_path = "/path/to/your/file.txt"
file_name_without_extension = os.path.splitext(os.path.basename(file_path))[0]
print(file_name_without_extension) # Output: file
pathlibfrom pathlib import Path
file_path = Path("/path/to/your/file.txt")
file_name_without_extension = file_path.stem
print(file_name_without_extension) # Output: file
Extracting file names from file paths in Python can be efficiently performed using built-in modules like os.path and pathlib. These methods provide robust solutions that handle various path formats and operating systems gracefully. Depending on your preferences or project requirements, you