出现错误:消息 SyntaxError:在 Python 中打开 txt 时语法无效

乘风 python 190

原文标题Getting Error: message SyntaxError: invalid syntax when open a txt in Python

code here

def button_clicked(self):
    self.lineedit.setText(
        open('test2.txt', 'r', encoding='uft_8')
        data = f.read()
        f.close()
        print(data))

错误消息SyntaxError:无效语法

预期的错误解决方案

原文链接:https://stackoverflow.com//questions/71521731/getting-error-message-syntaxerror-invalid-syntax-when-open-a-txt-in-python

回复

我来回复
  • Apollo-Roboto的头像
    Apollo-Roboto 评论

    你在错误的地方打开文件,试试这个:

    def button_clicked(self):
        f = open('test2.txt', 'r', encoding='uft_8')
        data = f.read()
        f.close()
        self.lineedit.setText(data)
    

    还有一种更好的方法可以从文件中打开读取数据

    def button_clicked(self):
        with open('test2.txt', 'r', encoding='uft_8') as f
            data = f.read()
            self.lineedit.setText(data)
    
    2年前 0条评论