How to get filename from a path in Python

Published on Aug. 22, 2023, 12:16 p.m.

To get the filename from a path in Python, you can use the os.path.basename() function. Here’s an example:

import os

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

In this example, we import the os module and define a path string (path) pointing to a file. We then use the os.path.basename() function to extract the filename from the path and store it in a new variable (filename). Finally, we print out the filename using the print() function.

Note that if the path points to a directory rather than a file, os.path.basename() will return the name of the directory, not the parent directory.

In general, you can use os.path.basename() to extract the filename from any path string, regardless of the operating system or path format.

Tags:

related content