我有这样的代码,
database = open(r"C:\Users\PC\Desktop\database.txt", "w")
print("Please type 1 if add a film")
enter = input("Enter: ")
if enter == "1":
film=input("Please write a film name: ")
database.write(film)
database.close()
当我重新打开程序时,txt 文件中的所有内容都消失了。我在写之前是怎么做的,我写的内容保存在 :)
最佳答案
使用 a
mode .
database = open(r"C:\Users\PC\Desktop\database.txt", "a")
w
模式将在您打开文件时截断文件(重写文件),同时这将追加到文件末尾。
要追加到新行中,只需:
if enter == "1":
film=input("Please write a film name: ")
database.write(film + "\n") #\n is the newline character
database.close()
关于python - 当我重新打开程序时,txt 文件中的所有内容都消失了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19752432/