是否可以在 python 中创建临时文件并在一段时间后删除?我检查了 tempfile生成临时文件和目录的库。
tempfile.TemporaryFile : This function creates tempfile which will be destroyed as soon as closed.
tempfile.NamedTemporaryFile: This function accepts a parameter delete. If delete is given the value false while calling the function the file will not be deleted on close.
我需要的是一个临时文件,即使在我关闭它后,我也应该能够用它的名字读取一段时间。但是,它应该会在一段时间后自动删除。
在 Python 2.7 中执行此操作的最简单方法是什么?
请您参考如下方法:
如果您只需要在您的 Python 程序中 每隔一段时间运行该文件,您可以将它用作上下文管理器:
def main(file_object):
# Can read and write to file_object at any time within this function
if __name__ == '__main__':
with tempfile.NamedTemporaryFile() as file_object:
main(file_object)
# Can still use file_object
# file_object is referencing a closed and deleted file here
如果您需要能够在 Python 程序之外打开它,比如在 main 结束后,就像在异步运行的进程中一样,您可能应该寻找更永久的解决方案(例如允许用户指定文件名。)
如果你真的需要一个临时的自动删除文件,你可以启动一个threading.Timer来在一段时间后删除它,但是要确保你的程序即使停止了也会删除它在计时器结束之前。
