从存储为字符串的文件路径中获取文件名

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

如何删除路径并仅在变量中保留文件名和扩展名?

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

我只想要例如 namefile.txt 而不是整个路径,例如 /path/to/namefile.txt

对于python3.4+, pathlib

from pathlib import Path

name = Path(Filename).name

首先,您需要清理字符串以使其跨平台工作,然后您可以只提取最后一部分。

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