【发布时间】:2012-12-26 12:46:17
【问题描述】:
我试图检查并删除现有的输出文件,并在新文件上写入。但是,我的代码似乎不起作用,因为它只捕获了上次迭代的输出。
# delete inactive contracts from dict()
for key, item in contracts.items():
if item['contract_status'] == 'Inactive':
del contracts[key]
else:
if os.path.exists(main_path):
try:
os.remove(main_path)
finally:
outfile = open(main_path, 'a')
outfile.write(item['name'])
outfile.write('\n')
outfile.close()
【问题讨论】:
-
你的最后一行真的有那个缩进级别吗?
-
请注意,在这里使用
try:finally:是没有意义的。您想编写文件然后在更高级别处理异常吗?另外,为什么不在finally套件中包含outfile.close()?