【发布时间】:2020-10-22 08:53:54
【问题描述】:
如何在 python 中将文本附加到 (file.txt) 文件中
这是我的程序代码:
file = open("file.txt", "a")
aa = 10
bb = 1
cc = 12
xx = 20
try:
if xx > aa:
file.write("Yes xx is greater than aa")
file.close()
elif xx < aa:
file.write("No xx is not greater than aa")
file.close()
if aa > xx:
file.write("Yes aa is greater than xx")
file.close()
elif aa < xx:
file.write("No aa is not greater than xx")
file.close()
if cc > xx:
file.write("Yes cc is greater than xx")
file.close()
elif cc < xx:
file.write("No cc is not greater than xx")
file.close()
except Exception as e:
print(e)
输出是:
我的问题是为什么只有第一个 if 和 elif 条件起作用并将该字符串写入文本文件,其余条件成功运行但字符串未附加到该文件中。
如果您能告诉我如何解决这个问题,我将不胜感激。
【问题讨论】:
-
文件在第一次写入后关闭(即条件成功)。
-
您应该在代码末尾关闭文件。
标签: python python-3.x append file-handling