python 2.7-使用Try:和Finally:删除现有文件并将新输出写入该文件



我试图检查并删除一个现有的输出文件,并写入一个新文件。然而,我的代码似乎不起作用,因为它只捕获了上一次迭代的输出。

# 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()

与其删除文件,不如打开它进行写入:

else:
    with open(main_path, 'w') as outfile:
        outfile.write(item['name'])
        outfile.write('n')

使用w打开文件会首先截断文件,因此写入文件的数据会替换旧内容。请注意,您正在为循环中的每个迭代编写文件。

通过将该文件用作上下文管理器(with ..(,它将自动关闭。

如果要将所有条目写入文件,请在循环的外部打开文件

with open(main_path, 'w') as outfile:
    for key, item in contracts.items():
        if item['contract_status'] == 'Inactive':
            del contracts[key]
        else:
            outfile.write(item['name'])
            outfile.write('n')

如果您只需要重写文件,如果contracts中没有非活动项目,请使用:

contracts = {k: v for k, v in contracts.iteritems() if v['contract_status'] != 'Inactive'}
if contracts:
    with open(main_path, 'w') as outfile:
        for contract in contracts.values():
            outfile.write(item['name'])
            outfile.write('n')

现在,您首先删除不活动的项目,然后如果还有剩余的合同,请将其写入文件。如果没有剩余,则main_path文件保持不变。

outfile = open(main_path, 'w') # this truncates existing file if any
# delete inactive contracts from dict()
for key, item in contracts.items():
    if item['contract_status'] == 'Inactive':
        del contracts[key]
    else:
        outfile.write(item['name'])
        outfile.write('n')
outfile.close()

应该把它改写成这样一个吗?

相关内容

最新更新