Python Forum
[Tkinter] How to get the name of a file only from a file path ?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tkinter] How to get the name of a file only from a file path ?
#1
I have been reading and experimenting to find the proper way to remove the path of a file when selected using filedialog.askopenfile.
When I select the file (mp3) from the folder I can use a print statement to check the value of the variable, which gives:
<_io.TextIOWrapper name='C:/Users/DT2000/Documents/Python Projects/mp3 Player/music/test.mp3' mode='r' encoding='cp1252'>
I would like to strip all of the path and trailing information so that only the test.mp3 will show when it is used in a Label for the song list.

Currently I have:
def audio_file():
    global recorded_file
    recorded_file = filedialog.askopenfile(title='J.E.C. Software Solutions',
    filetypes=[('Image Files', ['.wav', '.mp3', '.vox'])])
    now_playing.insert(0,recorded_file)
    print(recorded_file)
I have been reading information about the os.path.spitext and also ntpath.split but have not seen how this can help my sistuation.

A point in the right direction would be appreciated.
Reply
#2
Using https://docs.python.org/3/library/pathlib.html

from pathlib import Path

filepath = 'C:/Users/DT2000/Documents/Python Projects/mp3 Player/music/test.mp3'

path = Path(filepath)

print(path.name)
Output:
test.mp3
Reply
#3
I just found a way to do it but my attempt uses more lines of code.

Code:
def audio_file():
    global recorded_file
    recorded_file = filedialog.askopenfile(title='J.E.C. Software Solutions',
    filetypes=[('Image Files', ['.wav', '.mp3', '.vox'])])
    filepath = recorded_file
    path = Path(filepath)
    print(path.name)
Using this I receive:
expected str, bytes or os.PathLike object, not _io.TextIOWrapper
Reply
#4
What is filedialog.askopenfile

Edit found a ref to it in tkinter
If it is tkinter use askopenfilename() instead
http://effbot.org/tkinterbook/tkinter-file-dialogs.htm
Reply
#5
I have made the change and it is working properly, I appreciate the help.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Import a file and show file name on qcombobox GMCobraz 1 374 Jul-02-2020, 01:38 PM
Last Post: GMCobraz
  [Tkinter] Unable to get current contents of the entry field where the content is the file path pmpinaki 1 567 Apr-18-2020, 06:45 PM
Last Post: deanhystad
  [Tkinter] Tkinter - I need to read file excel from GUI app to script file johnjh 0 2,671 Apr-17-2020, 08:14 PM
Last Post: johnjh

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020