【问题标题】:Using Try: and Finally: to delete an existing file and write the new output to the file使用 Try: 和 finally: 删除现有文件并将新输出写入文件
【发布时间】: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()?

标签: python-2.7 try-finally


【解决方案1】:

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

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

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

通过将该文件用作上下文管理器 (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 文件将保持不变。

【讨论】:

  • 我试过你的代码,但结果还是一样。输出仅捕获最后一行。很奇怪!
  • @TingPing:这并不奇怪,因为每次循环迭代都会重新打开文件。已更新。
【解决方案2】:
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()

是否应该改写成这样的?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-04
    • 2015-06-11
    • 1970-01-01
    相关资源
    最近更新 更多