3 Easy Ways to Get Filename from Path in Python

There are the following methods to get a filename from the path in Python.

  1. “os.path.basename()”: It returns the base name in the specified path. 
  2. “os.path.split()”: It splits the path name into a pair of head and tail.
  3. “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.

Syntax

os.path.basename(path)

Arguments

The basename() method takes a single path-like object representing a file system path.

Example

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)

Output

app.py

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.

Syntax

os.path.split(path)

Arguments

The os.path.split() method takes a path-like object representing a file system path.

Example

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)

Output

app.py

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.

Example

import pathlib

path = '/Users/krunal/Desktop/code/pyt/app.py'

filename = pathlib.Path(path).name

print(filename)

Output

app.py

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.