How to Get Filename From Path in Python

  1. Use ntpath Library to Get the Filename From Path
  2. Use ntpath.basename() to Get the Filename From Path
  3. Python Get Filename From Path Using os.path.basename()
  4. Python Get Filename From Path Using os.path.split()

This tutorial introduces how to get filename from the path in Python. It also lists some example codes to further demonstrate the concepts associated with specific operating systems.

Use ntpath Library to Get the Filename From Path

Ways of defining a path can be different. The path of a file in Windows can use either backslash or forward slash as path separator. Therefore, the ntpath module will work for all paths on all platforms.

ntpath library supports a function that is basename. This function is passed a path and after execution, ntpath.basename(path) returns the filename from the given path. The basis example to use this method is shown below:

import ntpath
print(ntpath.basename("usr/temp/new/sample"))

Output:

sample

Use ntpath.basename() to Get the Filename From Path

This library will also work for Linux. However, in Linux, filenames may contain backslashes. So on Linux, r'usr/xyz\python' always refers to the file xyz\python in the usr folder.

import ntpath

print(ntpath.basename("r'usr/xyz\python"))

Output:

xyz\python

It refers to the filename python in the xyz subfolder of usr folder in Windows. We should know which platform we are using when both back and forward slashes are used in a path. Otherwise, you may not interpret the path correctly.

There is another way to get the filename from path that uses os.path.basename().

Python Get Filename From Path Using os.path.basename()

You can also use a function provided by the os.path library to get the filename from the path. The function is basename that is used to get the name of the file.

The basename takes a path as its parameter and returns the filename.

Below is the code example.

import os

print(os.path.basename("usr/temp/eng"))

Output:

eng

If the system is POSIX, and a windows-styled path containing double forward slashes is passed to os.path.basename(), the output will be the complete path given.

# in Linux
import os

print(os.path.basename("E:\\aws\\temp.jpg"))

Output:

E:\\aws\\temp.jpg

Python Get Filename From Path Using os.path.split()

If head and tail are required individually, the os.path.split() method can be used. This method takes path as its argument and returns head and tail of the path.

An example code is given below.

import os

head, tail = os.path.split("/Users/xyz/Downloads")
print(head)
print(tail)

Output:

/Users/xyz
Downloads