是的,我正在运行一个执行某些计算的while循环,最后将数据导出到.txt文件。问题是,它不是将数据附加到文件末尾,而是覆盖它并创建一个全新的文件。如何将其附加到旧文件?
这是我的代码:
turn = 1
while turn < times:
dip1 = randint(1,4)
dip2 = randint(1,4)
dip = (dip1 + dip2) - 2
adm1 = randint(1,4)
adm2 = randint(1,4)
adm = (adm1 + adm2) - 2
mil1 = randint(1,4)
mil2 = randint(1,4)
mil = (mil1 + mil2) - 2
with open("Monarchs Output.txt", "w") as text_file:
print("Monarch{}, adm: {}, dip: {}, mil: {}\n".format(turn, adm, dip, mil), file=text_file)
turn = turn + 1
请注意,它运行得很好,所有必需的导入都在代码的顶部。