如果发生错误,删除打开的文件

问题描述 投票:0回答:3

使用“with open()”时是否可以关闭和删除?

在名为“write_file”的例程中进行计算/提取/查询时,我偶尔会遇到错误。

try:
    with open(some_file, 'w') as report:
        write_file(report, other_variables)
except:
    logging.error("Report {} did not compile".format(some_file))

我将其包装在 try/ except 中,但它仍然将报告写入异常。

python contextmanager
3个回答
4
投票

如果您在遇到任何异常后愿意删除文件,那么这就足够了:

import os

try:
    with open(some_file, 'w') as report:
        write_file(report, other_variables)
except:
    logging.error("Report {} did not compile".format(some_file))
    os.remove(some_file)

请记住,具体说明您捕获的异常几乎总是更好。

一些免费建议:如果我担心向文件中写入无意义的内容,我会将您正在做的事情分成两个不同的步骤。

首先,我会在打开要写入的文件之前确定某些计算或语句是否会引发异常。如果是的话,我什至都懒得打开文件。

其次,如果第一步顺利通过,我将打开文件并写入内容。您可以选择将此步骤包含在 try/ except 块中以捕获文件 IO 错误。

像这样划分工作的好处是,如果发生问题,可以更轻松地诊断问题。第一步产生的异常类别必然与第二步产生的异常类别不同。


2
投票

这是我有时使用的一个方便的上下文管理器。它的好处是在删除部分文件的同时仍然引发异常:

from contextlib import contextmanager
from pathlib import Path


@contextmanager
def safe_open(file, *args, **kwargs):
    try:
        with open(file, *args, **kwargs) as f:
            yield f
    except:
        Path(file).unlink(missing_ok=True)
        raise

用途:

with safe_open('file.txt', 'wt') as f:
    raise RuntimeError('Oh no! Something went wrong! Well, at least file.txt gets deleted')

重要! 确保仅在模式

'w'
下使用它(打开以写入,首先截断文件)。它会很乐意删除打开供阅读的文件,这可能不是您想要的。


0
投票

经过一番挖掘,我发现,不,你无法关闭和删除打开的文件。在这种情况下,使用临时文件更有意义。如果报告正确符合要求,我就可以从临时文件中读取并写入实际的报告。这样,脚本就不会创建、写入然后删除实际文件。

with tempfile.TemporaryFile() as report:
    write_file(report, other_variables)

https://docs.python.org/3.4/library/tempfile.html

© www.soinside.com 2019 - 2024. All rights reserved.