【问题标题】:Why does only the last input appear in the text file? [duplicate]为什么只有最后一个输入出现在文本文件中? [复制]
【发布时间】:2017-01-12 03:19:57
【问题描述】:

我想将姓名和电话号码添加到名为 contacts.txt 的文件中

# ... previous code
number = raw_input("Choose a number: ")
if int(number) == 1:
    name = raw_input("Enter name: ")
    with open('contacts.txt','w') as f:
        f.write(name)
    no = raw_input("Enter phone number: ")
    with open('contacts.txt','w') as g:
        g.write(no)

输入姓名和数字后,文本文件中只出现数字。

输入姓名:sam

输入电话号码:69

contacts.txt 中的输出:

69

为什么我的名字没有出现?

我还添加了另一个 raw_input(所以我现在有 3 个)并且只写入了最后一个输入。

【问题讨论】:

  • 'w' 表示写入。您正在用电话号码覆盖内容
  • @LPK 哦。那么我怎样才能在文件中添加任何内容呢?
  • 将其更改为 'a' 以附加已建议的答案

标签: python


【解决方案1】:

您打开文件两次,每次都从头开始写入。这是因为您以'w'(写入)模式打开文件。

要么只打开一次文件,要么第二次以附加模式 ('a') 打开。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-15
    • 1970-01-01
    • 2021-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-21
    相关资源
    最近更新 更多