【发布时间】:2016-02-15 01:59:19
【问题描述】:
我有一个名为 output.txt 的文件,我想从代码周围的几个函数中写入该文件,其中一些是递归的。 问题是,每次我写的时候,我都需要一次又一次地打开文件,然后我之前写的所有东西都被删除了。 我很确定有一个解决方案,但在之前提出的所有问题中都没有找到它..
def CutTable(Table, index_to_cut, atts, previousSv, allOfPrevSv):
print ('here we have:')
print atts
print index_to_cut
print Table[2]
tableColumn=0
beenHere = False
for key in atts:
with open("output.txt", "w") as f:
f.write(key)
从另一个函数:
def EntForAttribute(possibles,yesArr):
svs = dict()
for key in possibles:
svs[key]=(yesArr[key]/possibles[key])
for key in possibles:
with open("output.txt", "w") as f:
f.write(key)
我的所有输出都是用其中一个函数编写的最后一个。
【问题讨论】:
-
以追加模式打开文件。
open("output.txt", "a") -
传递
f或使其全局化 -
当我在做这样的事情时,最初需要一个写入然后很多附加,我通常会做这样的事情:
with open('file.txt', 'w' if not os.path.isfile('file.txt') else 'a') as f: -
@Tgsmith61591 与
open('file.txt', 'a')的功能有何不同?