Extract filename from path in Python
Assuming that you have a variable object storing a file path, you can use the Python os.path.basename or the pathlib.Path.name functions in order to obtain the file name. Use the following syntax: os.path.basename(file_path) or pathlib.Path.name(file_path) for Python versions from 3.4 and onward.
#1 – Read a filename from path in Python with pathlib
In our first example we’ll use the pathlib library, which was added in Python 3.4.
Assume the following file system path object:
from pathlib import Path file_path = Path(r"C:\Temp\my_file.txt")
We can separate the filename from the path by using the name function of pathlib.Path name function:
file_name = file_path.name print(file_name)
This will return: my_file.txt
#2 – Trim the filename from directory with the os module
Other option for extracting the filw name is using the os module:
import os file_path = r"C:\Temp\my_file.txt" print (os.path.basename(file_path))
This will also return: my_file.txt
#3 – Get the file name with os.split
Another option is to extract the filename from the path using os.split. THis function returns a tuple consisting on the directory and name of the file.
import os file_path = r"C:\Temp\my_file.txt" firedir, filename = os.path.split(file_path) print(filename)
#4 – Get the filename without extension
In the next use case we would like to extract the file name without its fily type extension. This is easy with the Path.stem property that renders the path without the file suffix.
from pathlib import Path file_path = Path(r"C:\Temp\my_file.txt") file_name_no_extension = file_path.stem print(file_name_no_extension)
How to write a Python list object to a text file in your file system?