HOWTO · Python

How to Get Filename From Path in Python

This tutorial will demonstrate different methods in Python to extract the filename from a file path, including os.path.split(), os.path.basename(), ntpath.basename(), and pathlib.Path.name.

On this page

In programming, we often need to extract the filename from a given file path. Consider a scenario where we have a file path, such as C:\Documents\Project\file.txt, and we need to extract just the filename, i.e., file.txt. This is a routine task in file management, data analysis, and web development, and Python offers several ways to do it.

This tutorial introduces four methods to get a file name from a path in Python: os.path.split(), os.path.basename(), ntpath.basename(), and pathlib.Path.name. They differ mainly in what else they give you besides the filename, and in how they treat paths written for a different operating system than the one your code runs on.

Use the os.path.split() Function to Get Filename From Path in Python

The os.path.split() function splits a file path into its directory and filename components, so you can retrieve just the filename portion — or keep both parts, if you need the directory as well.

Syntax:

import os

directory, filename = os.path.split(path)

Parameters: The os.path.split() function accepts a single parameter.

  • path: This parameter represents the file path from which we want to extract the filename. It can be a string containing the absolute or relative path of the file.

Return Values: The function returns a tuple containing two elements.

  • directory: This variable holds the directory component of the path, excluding the filename.

  • filename: This variable contains the filename extracted from the path.

The following code snippet demonstrates how we can get a file name from a path in Python using the os.path.split() function.

import os

directory, filename = os.path.split("MyFolder/MySubFolder/MyFile.txt")
print(directory)
print(filename)

Output:

MyFolder/MySubFolder
MyFile.txt

The directory variable holds MyFolder/MySubFolder, the directory component of the file path, and the filename variable stores MyFile.txt, the extracted filename. Use this method when you need both parts; if you only need the filename, the next method is shorter.

Use the os.path.basename() Function to Get Filename From Path in Python

The os.path.basename() function returns the last component of a path, which is typically the filename. It is part of the os.path module, whose separator rules follow the operating system the code runs on.

Syntax:

import os

filename = os.path.basename(path)

Parameters: The os.path.basename() function accepts a single parameter.

  • path: This parameter represents the file path from which we want to extract the filename. It can be a string containing the absolute or relative path of the file.

Return Value: The function returns a string representing the extracted filename from the given path.

While both os.path.basename() and os.path.split() can extract filenames from paths, os.path.basename() focuses solely on the filename component and returns it as a string, which makes it the more straightforward choice when you do not need the directory part.

import os

filename = os.path.basename("MyFolder/MySubFolder/MyFile.txt")
print(filename)

Output:

MyFile.txt

The result, the filename MyFile.txt, is assigned to the variable filename and printed.

Use the ntpath Library to Get Filename From Path in Python

Python’s ntpath module implements path manipulation for Windows paths, whatever system your code actually runs on. That matters when you have to parse Windows-style paths on a Linux or macOS machine: there, os.path.basename() does not treat the backslash as a separator, so os.path.basename("MyFolder\\MySubFolder\\MyFile.txt") returns the whole string, while ntpath.basename() returns the filename.

Syntax:

import ntpath

filename = ntpath.basename(path)

Parameters: The ntpath.basename() function accepts a single parameter.

  • path: This parameter represents the file path from which we want to extract the filename. It can be a string containing the absolute or relative path of the file.

Return Value: The function returns a string representing the extracted filename from the given path.

The following code snippet demonstrates how we can get a file name from a Windows path in Python using the ntpath.basename() function.

import ntpath

filename = ntpath.basename("MyFolder\\MySubFolder\\MyFile.txt")
print(filename)

Output:

MyFile.txt

Use ntpath when the paths you process are Windows paths but your code may run anywhere; on a Windows machine, os.path already follows the same rules, so the two behave alike there.

Use the pathlib Module to Get Filename From Path in Python

The pathlib module provides an object-oriented approach to working with file paths. Its Path class encapsulates path-related operations, and the filename is available directly as the .name attribute of a Path object.

from pathlib import Path

filename = Path("MyFolder/MySubFolder/MyFile.txt").name
print(filename)

Output:

MyFile.txt

Beyond .name, the same object gives you the parent directory (.parent), the extension (.suffix), and the filename without the extension (.stem), which makes pathlib the convenient choice when you need more than just the filename.

Conclusion

We have explored 4 different methods in Python to extract the filename from a file path: os.path.split(), os.path.basename(), ntpath.basename(), and pathlib.Path.name. Each method has advantages and disadvantages, making them suitable for different scenarios.

The os.path.split() method can split a path into its directory and filename components. This granularity allows for more control over the path but requires additional code to access just the filename. However, it works across different operating systems, making it versatile.

On the other hand, os.path.basename() offers a simpler approach by directly extracting the filename from the path. It is compatible with various platforms and provides a straightforward solution. However, it only returns the filename as a string.

For Windows-specific paths, ntpath.basename() is designed to handle these paths on any operating system. It directly extracts the filename without the need for additional code. However, it is limited to Windows paths and lacks cross-platform compatibility.

Lastly, pathlib.Path.name provides an object-oriented approach for working with paths. It allows further path manipulation and integrates well with other pathlib functionalities. However, it introduces some complexity for simple filename extraction and requires importing the pathlib module.