3

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.

CrazyChucky
  • 3,263
  • 4
  • 11
  • 25

2 Answers2

8

For python3.4+, pathlib

from pathlib import Path

name = Path(Filename).name
kennyvh
  • 2,526
  • 1
  • 17
  • 26
  • TypeError: expected str, bytes or os.PathLike object, not tuple –  Mar 27 '21 at 23:50
  • @andreealombardo in your code, you use `askopenfilenames()`, which returns a tuple. Try `Path(Filename[0]).name` – kennyvh Mar 27 '21 at 23:52
  • 1
    It's worth pointing out, I think, that this works on any platform. Pretty much any method other than this requires manually mucking about with different path separators on Windows vs. Mac/Linux, and ain't nobody got time for that. – CrazyChucky Mar 28 '21 at 00:05
0

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]
tayler6000
  • 103
  • 1
  • 8