【问题标题】:readline() code in my python app works not correctly. Why?我的 python 应用程序中的 readline() 代码无法正常工作。为什么?
【发布时间】:2020-05-31 03:31:36
【问题描述】:

我正在使用 python3.8.3 和 pyqt5 构建一个应用程序。这是我的代码的一部分:

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)

当我调用这段代码时,输​​出是:

salam
[]

为什么数据是空的?有什么问题?

【问题讨论】:

  • 您是否检查过这些行是否已写入文件?如果文件仍然为空,则 file.readlines() 将返回一个空列表。
  • 是的。行已完成。

标签: file-handling python-3.8 readlines


【解决方案1】:

我认为问题在于没有关闭以写入模式打开的文件

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)

【讨论】:

    猜你喜欢
    • 2021-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-19
    • 1970-01-01
    • 1970-01-01
    • 2017-02-27
    相关资源
    最近更新 更多