Python-无法找到保存文本文档

时间:2017-02-04 20:47:41

标签: python save

我有一个要求数据的脚本,然后使用简单的file.open()和file.close()以及file.write()将其写入txt文档。每次运行脚本时,它都不会保存文档或覆盖它。如何获取我的.txt文档以反映多次运行的数据?如果我打开文档,它只包含我最近运行的程序中的数据。这是脚本:

name = input("What is your name?")

file = open("Python.txt","w") 

file.write("Next User ")
file.write(name)
file.write(" ")


ans1 = input("Which would you rather lose? a: an arm or b: a leg?")
file.write(ans1)

ans2 = input("What is your favorite primary color? a: red b: yellow c: blue")
file.write(ans2)

ans3 = input("Which do you like better? a: dogs b: cats c: birds d: hamsters e: lizards")
file.write(ans3)

ans4 = input("Do you prefer to a: talk to people b: text people or c: avoid people?")
file.write(ans4)

print("That's all for now!")
print("Here's your code: ",ans1,ans2,ans3,ans4)
print("Here's what other users got:")
file = open("Python.txt", "r") 
read = file.read()
print(read)
print("The last line is your own results.")

我将read = file.read()置于其中,因为当我使用print file.read()时,它会返回无效的语法'。 另外:如何写回程或输入密钥?

1 个答案:

答案 0 :(得分:0)

open接受第二个参数mode,指示应该读取或写入文件的方式。默认值为"r",对应于读取文本文件。适合附加到文本文件的值(如果不存在则创建它)是"a"。所以做这样的事情。

with open("my-file.txt", "a") as f:
    f.write("Fun text.\n")
    f.write("More fun text!\n")