How to Get the Filename from a Path in Python

09/09/2021

Contents

In this article, you will learn how to get the filename from a path in Python.

Get the Filename from a Path

You can get the filename from a file path in Python using the os.path module. The os.path module provides a number of useful functions for working with file paths. Here’s an example of how you can get the filename from a file path:

import os

file_path = '/path/to/file.txt'
filename = os.path.basename(file_path)
print(filename)

The above code uses the os.path.basename function, which returns the base name of a file path, i.e., the file name without the directory path. The basename function takes the file path as its argument and returns the file name as a string.

In the example above, the file path is /path/to/file.txt and the filename is file.txt. The code assigns the filename to the variable filename and then prints it.

 

The os.path module provides several other functions that can be used to manipulate file paths in Python. Here are a few of the most commonly used ones:

os.path.dirname(path)

Returns the directory name of a file path. This function returns the part of the file path that precedes the filename. For example, if the file path is “/path/to/file.txt”, the result of “os.path.dirname” would be “/path/to”.

os.path.split(path)

Returns a tuple containing the directory name and the base name of a file path. For example, if the file path is “/path/to/file.txt”, the result of os.path.split would be (‘/path/to’, ‘file.txt’).

os.path.join(path1, path2, …)

Joins two or more paths together. This function takes one or more file paths as arguments and returns a single file path that is the result of joining the individual paths together. For example, os.path.join(‘/path/to’, ‘file.txt’) would return “/path/to/file.txt”.

os.path.exists(path)

Returns True if the file path exists, and False otherwise. This function can be used to check if a file or directory exists before attempting to perform any operations on it.

os.path.isfile(path)

Returns True if the file path is a regular file, and False otherwise. This function can be used to check if a file is a regular file (as opposed to a directory, symbolic link, etc.).

os.path.isdir(path)

Returns True if the file path is a directory, and False otherwise. This function can be used to check if a file is a directory.

These are just a few of the functions provided by the os.path module. To learn more, you can refer to the official Python documentation: https://docs.python.org/3/library/os.path.html