gpt4 book ai didi

python - 尝试在 PyQT5 中打开文件时出现无效文件错误

转载 作者:太空宇宙 更新时间:2023-11-03 16:28:16 26 4
gpt4 key购买 nike

我正在尝试制作一个基本的文本编辑器,并且我正在使用 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())

任何帮助将不胜感激。

最佳答案

self.filename 是一个元组,因此显然您不能将其视为字符串,该方法返回两个元素,您需要第一个元素,因此解压:

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

或索引:

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

关于python - 尝试在 PyQT5 中打开文件时出现无效文件错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37822131/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com