python - 当我重新打开程序时,txt 文件中的所有内容都消失了

标签 python python-3.x

我有这样的代码,

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/

相关文章:

python - 高效地将行添加到 pandas DataFrame

python - 基于其他数组Python更新数组

Python - 对字典{String Key : List of Strings} by len(value)?进行排序

python - 在多处理循环中捕获异常

python - 在 python 中查找 List 长度的 O(1) 背后的原因

python - 赋值前引用的局部 (?) 变量

python - 列表搜索优化

Python - 在条件匹配时替换前 2 行

python - 在 Python argparse 中,是否可以配对 --no-something/--something 参数?

python - Pandas 无法打开 csv 文件 FileNotFoundError