删除 Python 程序留下的 shelve .dat 文件的简单方法?

发布于 2024-09-12 16:33:19 字数 161 浏览 2 评论 0原文

所以我有一个 python 程序,在执行后最终会留下一个来自 shelve 函数的 .dat 文件。我希望我的程序在完成后删除或清除该文件。我的教科书只提到如何创建 .dat 文件,但没有提到如何清除它。有什么好的命令可以解决这个问题吗?程序运行完成后,我不再需要 .dat 文件。

So I have a python program that ends up leaving a .dat file from the shelve function behind after execution. I would like my program to delete or clear that file once it is done. My textbook only mentions how to create a .dat file but not how to clear it. Any good commands out there to take care of this? I don't need the .dat file again after my program runs to completion.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

ぺ禁宫浮华殁 2024-09-19 16:33:19

这很简单:

import sys, os
sys.atexit.register( os.remove, path_to_file )

当 Python 解释器以正常(未终止/崩溃)方式存在时运行 os.remove( path_to_file ) 。但您需要确保该文件届时已关闭。

This is easy:

import sys, os
sys.atexit.register( os.remove, path_to_file )

runs os.remove( path_to_file ) when the Python interpreter exists in a normal (not killed/crashed) way. But you need to make sure the file is closed by then.

如痴如狂 2024-09-19 16:33:19

注册一个 atexit 处理程序来为您进行清理(如文档在这里)。

Register an atexit handler to do the cleanup for you (as described in the documentation here).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文