There are the following methods to get a filename from the path in Python.
- “os.path.basename()”: It returns the base name in the specified path.
- “os.path.split()”: It splits the path name into a pair of head and tail.
- “pathlib.Path().name”: It returns the complete filepath and applies the name property to it, which will return the filename.
Method 1: Use os.path.basename()
The easiest way to get the file name from the path is to use the “os.path.basename()” method. Working with UNIX or MacOS uses the slash / as the path separator, and Windows uses the backslash \ as the separator.
The basename() method takes a single path-like object representing a file system path.
To use the basename() function, import the os module at the top of the file.
import os The next step is to define the filepath. path = '/Users/krunal/Desktop/code/pyt/app.py'
You can see from the filepath that the filename is app.py.
To extract that from a filepath, use the os.path.basename() function.
import os path = '/Users/krunal/Desktop/code/pyt/app.py' basename = os.path.basename(path) print(basename)
You can see from the output that we got exactly what we requested.
When os.path.basename() method is used on a POSIX system to get the base name from a Windows-styled path; the complete path will be returned.
Method 2: Using os.path.split() method
The “os.path.split()” is a built-in Python method that “splits the pathname into a pair of head and tail”. The tail part will be our filename.
The os.path.split() method takes a path-like object representing a file system path.
The os.path.split() method returns head and tail. The tail is a filename, the head is a filepath, and we are interested in the filename.
import os path = '/Users/krunal/Desktop/code/pyt/app.py' head, tail = os.path.split(path) print(tail)
As you can see, the split() method returns head and tail values, and we printed the tail, which is the filename.
Method 3: Using pathlib.Path().name()
The pathlib module allows classes representing filesystem paths with semantics appropriate for different operating systems. For example, the Path() method returns the complete filepath and applies the name property to it, which will return the filename.
import pathlib path = '/Users/krunal/Desktop/code/pyt/app.py' filename = pathlib.Path(path).name print(filename)