1

So I have a FileDialogue Object in Tkinter that gets the location of a file from the User's Computer.

The output is not always the same as the directory may vary.

For E.G. = Filename = C:/MusicDirectory/Music.mp3, or it can be something else too, like D:/Some/Directory/IDontKnowWhatToTypeAnyMore/Music.mp3

My main objective is to remove the "C:/MusicDirectory/" and the unwanted Directory from the string, but the string does not remain the same. It can be some other folder too.

Can someone help me in this situation?

XTRAP
  • 108
  • 1
  • 10
  • 1
    So you want to just get the filename? – ssp Dec 13 '20 at 06:39
  • Yes, @Moosefeather, I just want to get the filename. Like, the filename is `something.mp3` and I just want to get that name and not the directory like `C:/` – XTRAP Dec 13 '20 at 06:41
  • 1
    Lots of good discussion about this issue here: https://stackoverflow.com/questions/8384737/extract-file-name-from-path-no-matter-what-the-os-path-format – Curt Welch Dec 13 '20 at 06:46

2 Answers2

1

What you want is os.path.basename:

os.path.basename('C:/MusicDirectory/Music.mp3') # 'Music.mp3'

os.path.basename('D:/Some/Directory/IDontKnowWhatToTypeAnyMore/Music.mp3') # 'Music.mp3'
ssp
  • 1,666
  • 11
  • 15
  • Thank You M8, that was what I was looking for. – XTRAP Dec 13 '20 at 06:47
  • 1
    @xpDev glad I could help, you can also check out the [`pathlib.PurePath`](https://docs.python.org/3/library/pathlib.html#pathlib.PurePath) object which could be convenient if you're doing other operations on the path. (In this case if you'd use [`PurePath.name`](https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.name)) – ssp Dec 13 '20 at 06:51
  • 1
    Thanks @MooseFeather for your effort. – XTRAP Dec 13 '20 at 06:52
1

First using method os.path.basename ( recommended ):

os.path.basename('C:/MusicDirectory/Music.mp3')

Second method:

path = 'C:/MusicDirectory/Music.mp3'
partsOfPath = path.split("/")
nameOfFile = partsOfPath[-1]
Manbir Judge
  • 113
  • 1
  • 13