user15496986
user15496986

Reputation:

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

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.

Upvotes: 5

Views: 5971

Answers (2)

tayler6000
tayler6000

Reputation: 101

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]

Upvotes: -1

kennyvh
kennyvh

Reputation: 2854

For python3.4+, pathlib

from pathlib import Path

name = Path(Filename).name

Upvotes: 13

Related Questions