0

I'm trying to handle an exception when someone exits out of the file dialogue screen without selecting a file. I was told that when this occurs, the filepath variable would be saved as "". If that's actually the case, can anyone tell me why the is statement isn't handling that case?

PYQT documentation says this about getOpenFileName: "This is a convenience static function that returns an existing file selected by the user. If the user presses Cancel, it returns a null string."

Any ideas?

    def getfile(self):
        filepath = QFileDialog.getOpenFileName(self, 'Open MP3 File',
                                                        '', "MP3 (*.mp3)")
      
        self.load_info.setText("File Location: " + filepath)

        return filepath

    def shred(self, filepath):

        try:
            filepath

        except NameError:
            self.load_info.setText("You Must First Load A MP3 File To Shred!")

        if filepath == "":
            self.load_info.setText("You Must First Load A MP3 File To Shred!")

        else:
            self.button_shred.setText("Shredding! Please Wait!")
  • As your documentation cite said you'll get a null string in return. Thats different than an empty string. https://stackoverflow.com/questions/16620354/difference-between-null-and-empty-string – Oivalf Aug 19 '22 at 09:06
  • @Oivalf maybe that's the case in Java, but that's Python here, so what would it be? – Thierry Lathuille Aug 19 '22 at 09:08
  • @ThierryLathuille, whops your right. Andrew can't you just debug it? For example place a breakpoint, and access the filepath value in the exit case? – Oivalf Aug 19 '22 at 09:21
  • 1
    As shown in the documentation of [`getOpenFileName()`](https://www.riverbankcomputing.com/static/Docs/PyQt5/api/qtwidgets/qfiledialog.html#getOpenFileName) (and as seen by printing its result or calling `help(QFileDialog.getOpenFileName)`), it returns a *tuple*, composed of the file path (or an empty string if the dialog is cancelled) and the selected filter. Use `filepath, filter = QFileDialog.getOpenFileName(...)`. – musicamante Aug 19 '22 at 10:08

0 Answers0