Search code examples
file-handlingpython-3.8readlines

readline() code in my python app works not correctly. Why?


I am building an app by python3.8.3 and pyqt5. This is a part of my code:

def logupd(self):
        users=open('NeveshtarUsers.txt', 'w')
        users.write('Username: ')
        users.write(self.user2.text())
        users.write(' Password: ')
        users.write(self.pass2.text())
        users.write('.\n')
        users.write('Name: ')
        users.write(self.name.text())
        users.write('.\n')
        users.write('....................\n')
        self.no.setText('Loggind up has succesed. Please Login')

        with open('NeveshtarUsers.txt') as file:
            print('salam')
            data = file.readlines()
            print(data)

When I call this code, the output is:

salam
[]

Why data is empty? What's the problem?


Solution

  • I think the problem is not closing the file that is open in write mode

    def logupd(self):
            users=open('NeveshtarUsers.txt', 'w')
            users.write('Username: ')
            users.write(self.user2.text())
            users.write(' Password: ')
            users.write(self.pass2.text())
            users.write('.\n')
            users.write('Name: ')
            users.write(self.name.text())
            users.write('.\n')
            users.write('....................\n')
            self.no.setText('Loggind up has succesed. Please Login')
            # close the file that is opened in write , the text will get updated to the system's memory 
            # only when the file is closed 
            users.close()
            with open('NeveshtarUsers.txt') as file:
                print('salam')
                data = file.readlines()
                print(data)