为什么只有最后一个输入出现在文本文件中?

时间:2017-01-11 19:17:22

标签: python

我想在名为const std::vector<std::string> v1{"A", "B", "C"}, v2{"D", "E", "F"}; for (const auto& s : ranges::view::concat(v1, v2)) { std::cout << s << std::endl; }

的文件中添加姓名和电话号码
contacts.txt

输入姓名和号码后,只有该号码出现在文本文件中。

  

输入姓名:sam

     

输入电话号码:69

# ... 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) 中的输出:

  

69

为什么我的名字不出现?

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

1 个答案:

答案 0 :(得分:0)

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

只打开一次文件,或者第二次以追加模式('a')打开文件。

相关问题