Examples
- How to Create Directory in Python? New and If Not Exists
- How to Change Directory in Python? Change Current Working Directory
- How to Get Current Working Directory in Python?
- How to Remove Directory in Python? (Empty & With Files)
- How to Copy Directory in Python? Program With Examples
- How to Open Directory in Python? Program & Example
- How to Read All Files in Directory in Python? (All Types of Files)
- How to Copy File in Python From One Directory to Another? (With and Without shutil)
- Python File Append Program (Append to File)
- How to Read Text File in Python Line by Line? (3 Ways)
- How to Get File Name From File Path in Python?
- Get Number of Lines in File in Python (Line Count)
- How to Get Size of File in Python? (File Size Program)
How to Get File Name From File Path in Python?
When working with file paths in Python, it's often necessary to extract the file name from the given path. Whether you're organizing files, performing file-related operations, or simply displaying information, getting the file name from a file path is a common requirement.
So, in this post, we will learn how to get the file name from a file path in Python, allowing you to work with file names independently and perform various file handling tasks with ease.
Python provides convenient methods and modules for working with file paths, enabling us to manipulate and extract specific components of a path. By using these methods, you can effortlessly isolate the file name from a given file path, regardless of its format or location.
Get File Name from File Path in Python
We can use the os.path module for finding the filename from file path. Specifically, the os.path.basename() function returns the base name (i.e., the file name) from a given path.
Code
import os
def get_file_name(file_path):
file_name = os.path.basename(file_path)
return file_name
# Example usage
file_path = "/path/to/file.txt"
file_name = get_file_name(file_path)
print("File name:", file_name)
Output
File name: file.txt
Explanation
In the above program, the get_file_name() function takes the file path as an argument. It uses os.path.basename() to extract the file name from the path and assigns it to the file_name variable. Finally, it returns the file name.
To use this program, replace "/path/to/file.txt" with the actual file path from which you want to extract the file name. The program will then print the extracted file name.