Get filename from Path in Python

Get filename from path in Python

There are different ways to define the path of the file. In Windows, the path separator for a file can be either a backslash or a forward slash. The ntpath module of Python will work on all platforms for all paths. The forwardslash / is used for UNIX and MacOS operating system and backslash \ for windows os.

This article will introduce some methods to get the filename from path in python. It also includes some sample code to help illustrate the ideas associated with different operating systems.

Get filename from Path in Python using the ntpath Module

Windows

On Windows systems, the ntpath module offers os.path capability. It may also be used on other platforms to handle Windows paths. The basename() function is supported by the ntpath library. ntpath.basename(path) is a function that is supplied a path and returns the filename from that path after execution.

The code example is given below.

The output is:

demo.txt

Linux

This module is Linux compatible. Filenames on Linux, on the other hand, may contain backslashes. So, for Linux, r’Users/Public\test’ always refers to the User folder’s Public\test file.

The code example is given below.

The output is:

demo.txt

When both back and forward slashes are used in a path, we should know which platform we are using. Otherwise, we might not be able to appropriately understand the path.

Get filename from Path in Python using the os.path.basename() Function

In this method, we use a function basename() that is provided by the os.path library. The basename() function uses the file path as a parameter and it will return the name of the file.

The code example is given below.

The output is:

demo.txt

This function works with any path format supported by the operating system.

Get filename from Path in Python using the os.path.split() Function

If we want to extract the head and tail of the file path, we can use this function. The file path is taken as an argument and the function split the head and tail of it.

The code example is given below.

The output is:

Users\Public\test
demo.txt

Get filename from Path in Python using the pathlib.path().name Method

The Pathlib module offers classes with semantics suited for multiple operating systems to represent file system paths. The Path() function returns the whole filepath, which we can then use with the name field to get the filename.

The code example is given below.

The output is:

demo.txt

Conclusion

os.path.basename or os.path.split won’t work in all the cases. If you are running a script on Linux and try to get windows path, it will fail. You can use npath.basename() which will work in all the scenarios.

That’s all about how to get filename from Path in Python

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *