pythonpyqtpyqt5qtmultimedia

Get file name from an opened file, not a file path


Let's say I opened a file called file1.mp3 in a PyQt5 app using the file dialog and assigned it to a variable like this:

song = QFileDialog.getOpenFileName(self, "Open Song", "~", "Sound Files (*.mp3 *.ogg *.wav *.m4a)")
print(song[0])
url = QUrl.fromLocalFile(song[0])
self.playlist.addMedia(QMediaContent(url))

How can I get the file name instead of a file path so I can display it in a statusBar? Or even better, is there a "now playing"-like function I could use or create?


Solution

  • There are several simple ways to get the name of a file:


    song, _ = QFileDialog.getOpenFileName(self, "Open Song", "~", "Sound Files (*.mp3 *.ogg *.wav *.m4a)")
    print(song)
    url = QUrl.fromLocalFile(song)
    self.playlist.addMedia(QMediaContent(url))
    your_statusbar.showMessage("now playing {}".format(url.fileName()))
    

    song, _ = QFileDialog.getOpenFileName(self, "Open Song", "~", "Sound Files (*.mp3 *.ogg *.wav *.m4a)")
    print(song)
    url = QUrl.fromLocalFile(song)
    self.playlist.addMedia(QMediaContent(url))
    filename = QFileInfo(song).fileName()
    your_statusbar.showMessage("now playing {}".format(filename))
    

    song, _ = QFileDialog.getOpenFileName(self, "Open Song", "~", "Sound Files (*.mp3 *.ogg *.wav *.m4a)")
    print(song)
    url = QUrl.fromLocalFile(song)
    self.playlist.addMedia(QMediaContent(url))
    
    from pathlib import Path    
    
    filename = Path(song).name
    your_statusbar.showMessage("now playing {}".format(filename))
    

    song, _ = QFileDialog.getOpenFileName(self, "Open Song", "~", "Sound Files (*.mp3 *.ogg *.wav *.m4a)")
    print(song)
    url = QUrl.fromLocalFile(song)
    self.playlist.addMedia(QMediaContent(url))
    
    import os   
    
    filename = song.rstrip(os.sep)
    your_statusbar.showMessage("now playing {}".format(filename))
    

    or:

    song, _ = QFileDialog.getOpenFileName(self, "Open Song", "~", "Sound Files (*.mp3 *.ogg *.wav *.m4a)")
    print(song)
    url = QUrl.fromLocalFile(song)
    self.playlist.addMedia(QMediaContent(url))
    
    import os   
    
    _ , filename = os.path.split(os.sep)
    your_statusbar.showMessage("now playing {}".format(filename))