【问题标题】:Why doesn't my txt file save after my write() - Python 3为什么我的 txt 文件在我的 write() 之后没有保存 - Python 3
【发布时间】:2020-10-30 09:44:04
【问题描述】:

我正在尝试制作一个基本的数据加密程序,将用户名和密码存储到一个 txt 文件中,但是当我的程序写入数据时它不会保存,因此下次它会覆盖现有数据。

def write_file(username, password):
    f = open(r"C:\Users\victo\Downloads\incrypted_data.txt", 'w')
    data = username+' '+password
    f.write(data)
    f.close()

write_file(username, password)

【问题讨论】:

  • 您可以使用open(r"C:\Users\victo\Downloads\incrypted_data.txt", 'a') 而不是w,这将附加到您的文件中,请参阅here
  • 运行python,输入help(open) 并阅读您传递给它的w 的含义。 (我只是根据“它被写入现有数据”进行猜测,老实说,您的要求尚不清楚。)
  • 使用w 文件模式,如果文件存在,它会截断文件。如果你想追加,试试a

标签: python python-3.x file text write


【解决方案1】:

打开文件时需要使用追加模式('a'),而不是写入模式('w')。 将您的代码更改为:

def write_file(username, password):
    f = open(r"C:\Users\victo\Downloads\incrypted_data.txt", 'a')
    data = username+' '+password
    f.write(data)
    f.close()

write_file(username, password)

【讨论】:

    猜你喜欢
    • 2011-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多