程序退出时如何删除文件? [关闭]

2024-03-25

有没有办法注册一个文件,以便在Python退出时将其删除,无论它如何退出?我正在使用长期存在的临时文件,并希望确保它们被清理。

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


Use the tempfile module http://docs.python.org/2/library/tempfile.html;它创建自动删除的临时文件。

来自tempfile.NamedTemporaryFile()文档 http://docs.python.org/2/library/tempfile.html#tempfile.NamedTemporaryFile:

If delete为 true(默认值),文件一关闭就会被删除。

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

另一种方法是创建一个专用的临时目录,其中tempdir.mkdtemp() http://docs.python.org/2/library/tempfile.html#tempfile.mkdtemp,并使用shutil.rmtree() http://docs.python.org/2/library/shutil.html#shutil.rmtree当程序完成时删除整个目录。

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

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

You could这样做与atexit钩子函数 http://docs.python.org/2/library/atexit.html,但是上下文管理器是much更清洁的方法。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

程序退出时如何删除文件? [关闭] 的相关文章

随机推荐