【问题标题】:Unable to write to file in python无法在python中写入文件
【发布时间】:2020-04-26 09:31:17
【问题描述】:

我正在尝试将用户输入写入 python 中的文件,但它不起作用。这是我的代码:

filename='guest_book.txt'
while True:
    with open(filename,'a') as file_object:
        name=input('Please enter your name')
        file_object.write(name)
        file.object.write('visit the website')
        print('Hello')

【问题讨论】:

  • 请添加更多上下文
  • 会发生什么(输出,完整的错误消息),应该发生/显示什么?编辑问题以显示它。
  • 您似乎试图将代码重新输入问题框中,而不是复制粘贴。在这样做的过程中,您引入了实际代码与您发布的内容之间的差异。相反,请从您实际运行的文件中复制粘贴代码。
  • while True ?这就像无限/永无止境,要求您输入名称。 file.object.write('visit the website') 也应该是 file_object.write('visit the website')

标签: python python-3.x file


【解决方案1】:

有些系统只有在缓冲区中有一定数量的数据要发送时才会写入文件。或者有时会发生的情况是在您关闭文件之前不会写入文件。

无论如何,此代码适用于 W10 x64 Python 3.7。该文件会按照您的预期动态更新。

exit_loop = False
filename='guest_book.txt'

while exit_loop == False:

    with open(filename,'a') as file_object:

        name=input('Please enter your name: ')
        if name == 'xxx':
            exit_loop = True
        else:
            file_object.write(name)
            file_object.write('visit the website')

【讨论】:

  • file_object.close() ?为什么?
  • 文件在每次循环迭代中都会关闭,因为with 块被留下。
猜你喜欢
  • 1970-01-01
  • 2014-09-03
  • 2014-08-21
  • 1970-01-01
  • 1970-01-01
  • 2020-12-16
  • 2018-03-26
  • 2015-12-16
  • 1970-01-01
相关资源
最近更新 更多