How to extract and get a file name from a path in Python?

Extract filename from path in Python

Use the following syntax in order to obtain the file name from a variable object that stores your a path in Python:

# option 1
import os

# option 2
from pathlib import Path

Note: Option 2 (using the Path module) is available in Python versions from 3.4 and onward.

#1 – Read filename from path in Python with pathlib example

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 =

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)

#4 – Get directory from the path in Python

Next we would like to get the file parent directory from the path:

from pathlib import Path
file_path = Path(r"C:\Temp\my_file.txt")
file_directory = file_path.parent
print("The file parent directory is: " + str(file_directory))

This will return the following result in:

The file parent directory is: C:\Temp

Note: I had to cast / convert the file directory from a Windows Path (because i am using Windows) to a string in order to concatenate it into the print statement.

#5 – Get the filename without extension

In the next use case we would like to extract the file name without its file 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

#6 – Split filename and extension

In a similar fashion we are able to get tet the name of the file and extension from the path.

from pathlib import Path
file_path = Path(r"C:\Temp\my_file.txt")
file_name = file_path.stem
file_extension = file_path.suffix
print("The file name is: " + file_name)
print("The file extension is: " + file_extension)

This returns the following result:

The file name is: my_file
The file extension is: .txt

Related learning

How to write a Python list object to a text file in your file system?