【问题标题】:Invalid file error when trying to open file in PyQT5尝试在 PyQT5 中打开文件时出现无效文件错误
【发布时间】:2016-10-15 18:47:56
【问题描述】:

我正在尝试制作一个基本的文本编辑器,并且我正在使用 PYQT5 来执行此操作,但是当我尝试打开或保存文件时出现错误,打开时我得到:

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 (*.*)')

通过保存我得到:

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'

这是我为这些功能所拥有的:

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

任何帮助将不胜感激。

【问题讨论】:

    标签: python python-3.x pyqt qt5 pyqt5


    【解决方案1】:

    self.filename 是一个元组,所以显然你不能把它当作一个字符串,有两个从方法返回的元素,你想要第一个这样解包:

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

    或索引:

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-06
    • 2017-10-02
    • 2013-02-06
    • 2016-11-03
    相关资源
    最近更新 更多