Python - How to get file name from file path

1 year ago
2

How to get file name from file path in python

To extract the file name from a file path in Python, you can use the os.path.basename function from the os module or the Path.name attribute from the pathlib module.

Here's how you can do it with both methods

Using os.path.basename function

import os

file_path = '/path/to/your/file.txt'
file_name = os.path.basename(file_path)

print(file_name)

Loading comments...