Hunter Stewart
Hunter Stewart

Reputation: 23

Invalid file error when trying to open file in PyQT5

I am trying to make a basic text editor and I am using PYQT5 to do so however when I try to open or save a file I get errors, for open I get:

File "D:\NicKLz\Documents\GitHub\MiscProjects\TextEditor\txtEditor.py", line 81, in open
    with open(self.filename, "r") as file:
TypeError: invalid file: ('D:/NicKLz/Documents/GitHub/MiscProjects/TextEditor/Hello.writer', 'Files (*.*)')

And with save I get:

File "D:\NicKLz\Documents\GitHub\MiscProjects\TextEditor\txtEditor.py", line 89, in save
    if not self.filename.endswith(".writer"):
AttributeError: 'tuple' object has no attribute 'endswith'

Here is what I have for those functions:

def open(self):
    #Get filename and show only .txt files
    self.filename = QtWidgets.QFileDialog.getOpenFileName(self, 'Open File', ".", "Files (*.*)")

    if self.filename:
        with open(self.filename, "r") as file:
            self.text.setText(file.read())

def save(self):
    #Only Open this dialog if there is no filename yet
    if not self.filename:
        self.filename = QtWidgets.QFileDialog.getSaveFileName(self, "Save File")
    #Add the appropriate extension if not currently in place
    if not self.filename.endswith(".writer"):
        self.filename += ".writer"

    #Store Contents and format in html format which QT does a nice job of implementing for us already
    with open(self.filename,"w") as file:
        file.write(self.text.toHtml())

Any help would be really appreciated.

Upvotes: 1

Views: 972

Answers (1)

Padraic Cunningham
Padraic Cunningham

Reputation: 180512

self.filename is a tuple so obviously you cannot treat it as a string, there are two elements returned from the method, you want the first so unpack:

self.filename, _ = QtWidgets.QFileDialog.getOpenFileName(self, 'Open File', ".", "Files (*.*)")

Or index:

self.filename = QtWidgets.QFileDialog.getOpenFileName(self, 'Open File', ".", "Files (*.*)")[0]

Upvotes: 1

Related Questions