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

error message SyntaxError: invalid syntax

Expected error resolution



Solution 1:[1]

Your are opening the file in the wrong place, try this:

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

also there is a better way to open read data from a file

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Apollo-Roboto