0

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

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

2 回答 2

2

不要删除文件,只需打开它进行写入:

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文件保持不变。

于 2012-12-26T12:49:46.533 回答
1
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()

应该改写成这样的吗?

于 2012-12-26T12:59:06.137 回答