How to Get the Last Part of the Path in Python?
In this article, we will learn how one can get the last part of the path in Python. We will use some built-in functions, and some custom codes as well to better understand the topic.
We will look at two modules of Python -
os Module and
os Module in Python provides three different functions to extract the last part of the path.
pathlib Module in Python also provides a function to get the last part of the path. Let us discuss these functions separately.
Get the Last Part of the Path using OS Module
os module in Python has various functions to interact with the operating system. It provides
os.path , a submodule of the os module for the manipulation of paths. We will use the three functions of os.path to get the last part of the path in Python.
Example: Use os.path.normpath() and os.path.basename()
This method uses
os.path.basename() together to find the last part of the given path.
os.path.normpath() - It removes all the trailing slashes from the given path. It is passed as an argument to os.path.basename().
os.path.basename() - It returns the last part of the path.
import os path = os.path.basename(os.path.normpath('/folderA/folderB/folderC/folderD/')) print(path)
Example: Use os.path.split()
This method uses
os.path.split() to find the last part of the path. As the name suggests, it splits the path into two - head part and tail part. Here, the tail is the last pathname component and the head is everything leading up to that. The tail part will never contain a slash; if the name of the path ends with a slash, the tail will be empty. This example returns the last part of the path i.e. tail part.
import os path = '/home/User/Desktop/sample.txt' # Split the path in head and tail pair head_tail = os.path.split(path) # print tail part of the path print(head_tail)
Get the Last Part of the Path using Pathlib Module
pathlib module provides
PurePath() function to get the last part of the path.
path.name prints the last part of the given path. If you are confused between Path and PurePath, PurePath provides purely computational operations while Path or we can say "concrete path" inherits from the PurePath provides I/O operations.
Example: Use pathlib.PurePath()
import pathlib path = pathlib.PurePath('/folderA/folderB/folderC/folderD/') print(path.name)
In this article, we learned to find the last part of the given path by using built-in functions such as
os.path.normpath(), os.path.split(), pathlib.PurePath() and different examples to extract the last part. These functions will work in all cases.