Get just the filename from a file path stored as a string

Viewed 113

How can I remove the path and leave only the filename and extension inside a variable?

root=tk.Tk()
root.withdraw()
FileName=filedialog.askopenfilenames()
print(Filename)

I want only for example namefile.txt and not the whole path, like /path/to/namefile.txt.

2 Answers

For python3.4+, pathlib

from pathlib import Path

name = Path(Filename).name

First, you need to sanitize the string so it works cross-platform, then you can just pull the last section.

filename = filename.replace('\\', '/') # Turns the Windows filepath format to the Literally everything else format.
filename = filename.split('/')[-1]
Related