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

chaNcharge picture chaNcharge · Mar 11, 2018 · Viewed 8.6k times · Source

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?

Answer

eyllanesc picture eyllanesc · Mar 11, 2018

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

  • Using QUrl:

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()))
  • Using QFileInfo:

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))
  • Using pathlib:

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))
  • Using os:

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))