简体   繁体   中英

Python- Can't find a way to save a txt doc

I have a script that asks for data, then writes it into a txt document using simple file.open() and file.close() and file.write(). Every time I run the script it either doesn't save the document or overwrites it. How do I get my .txt document to reflect data from across multiple runs? If I open the document, it only contains data from my most recent run of the program. Here's the script:

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.")

I put the read = file.read() in because when I use print file.read() it returns 'invalid syntax'. Also: How do I have it write a return or enter key?

open takes a second argument, mode , indicating the manner in which the file should be read or written. The default value is "r" , which corresponds to reading a text file. The value suitable for appending to a text file (creating it if it doesn't exist) is "a" . So do something like this.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM