程序退出时如何删除文件? [英] How to remove file when program exits?

查看:48
本文介绍了程序退出时如何删除文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法注册一个文件,让它在Python退出时被删除,不管它如何退出?我正在使用长期存在的临时文件并希望确保它们被清理.

Is there a way to register a file so that it is deleted when Python exits, regardless of how it exits? I am using long-lived temporary files and want to ensure they are cleaned up.

该文件必须有一个文件名,并且它的原始句柄应该尽快关闭——将创建数千个这样的文件,我需要确保它们仅作为普通文件存在.

The file must have a filename and it's original handle should be closed as soon as possible -- there will be thousands of these created and I need to ensure they exist only as normal files.

推荐答案

使用 tempfile 模块;它会创建自动删除的临时文件.

Use the tempfile module; it creates temporary files that auto-delete.

来自 tempfile.NamedTemporaryFile() 文档:

From the tempfile.NamedTemporaryFile() documentation:

如果 delete 为 true(默认值),文件会在关闭后立即删除.

If delete is true (the default), the file is deleted as soon as it is closed.

您可以使用这样的文件对象作为上下文管理器,使其在代码块退出时自动关闭,或者在解释器退出时保持关闭.

You can use such a file object as a context manager to have it closed automatically when the code block exits, or you leave it to be closed when the interpreter exits.

另一种方法是创建一个专用的临时目录,使用 tempdir.mkdtemp(),并使用 shutil.rmtree() 在程序完成时删除整个目录.

The alternative is to create a dedicated temporary directory, with tempdir.mkdtemp(), and use shutil.rmtree() to delete the whole directory when your program completes.

最好使用另一个上下文管理器执行后者:

Preferably, you do the latter with another context manager:

import shutil
import sys
import tempfile

from contextlib import contextmanager


@contextmanager
def tempdir():
    path = tempfile.mkdtemp()
    try:
        yield path
    finally:
        try:
            shutil.rmtree(path)
        except IOError:
            sys.stderr.write('Failed to clean up temp dir {}'.format(path))

并将其用作:

with tempdir() as base_dir:
    # main program storing new files in base_dir

# directory cleaned up here

可以使用atexit钩子函数来做到这一点,但上下文管理器是一种更简洁的方法.

You could do this with a atexit hook function, but a context manager is a much cleaner approach.

这篇关于程序退出时如何删除文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆