如何用Python在软件关闭时删除仅含数字无扩展名的文件?
解决方案
要实现软件关闭时删除当前目录下所有文件名仅含数字的临时文件,你可以通过以下步骤完成:
1. 编写清理函数
遍历当前工作目录,筛选出符合条件的文件并删除,同时注意跳过自身可执行文件(避免误删):
from pathlib import Path import atexit import sys def cleanup_temp_files(): current_dir = Path.cwd() # 获取编译后可执行文件的名称(避免误删自身) if getattr(sys, 'frozen', False): # PyInstaller编译后的状态 exe_name = Path(sys.executable).name else: # 脚本运行状态 exe_name = Path(__file__).name for file in current_dir.iterdir(): if file.is_file(): # 检查文件名是否仅含数字,且不是自身可执行文件 if file.name.isdigit() and file.name != exe_name: try: file.unlink() except Exception as e: # 处理文件占用等删除失败的情况 print(f"删除文件失败: {file.name} - {str(e)}")
2. 注册退出钩子
使用atexit模块注册清理函数,确保软件正常退出或异常退出(除强制杀死进程外)时自动执行清理:
# 注册清理函数,程序退出时自动调用 atexit.register(cleanup_temp_files)
3. 结合GUI程序的额外处理
如果你的软件是GUI程序(比如用Tkinter、PyQt等),建议同时在窗口关闭事件中触发清理,确保关闭窗口时立即执行:
以Tkinter为例:
import tkinter as tk root = tk.Tk() def on_close(): cleanup_temp_files() root.destroy() # 绑定窗口关闭事件 root.protocol("WM_DELETE_WINDOW", on_close) root.mainloop()
代码整合示例
把清理逻辑和你现有的代码结合,完整片段大概是这样:
from pathlib import Path import subprocess import mysql.connector import atexit import sys def cleanup_temp_files(): current_dir = Path.cwd() if getattr(sys, 'frozen', False): exe_name = Path(sys.executable).name else: exe_name = Path(__file__).name for file in current_dir.iterdir(): if file.is_file() and file.name.isdigit() and file.name != exe_name: try: file.unlink() except Exception as e: print(f"删除失败: {file.name} - {e}") # 注册退出清理 atexit.register(cleanup_temp_files) def writeTofile(data, path): # 你的文件写入逻辑 with open(path, 'wb') as f: f.write(data) def view_document(docID): conn = mysql.connector.connect( host='your_host', user='your_user', password='your_password', database='your_db' ) cursor = conn.cursor() cursor.execute("SELECT DOC_COPY FROM DOC_STORE WHERE DOC_ID=%s", (docID, )) docCopy = cursor.fetchone()[0] cursor.close() conn.close() docPath = Path.cwd().joinpath(f"{docID}") writeTofile(docCopy, docPath) subprocess.run(['open', docPath], check=True) # 你的程序主逻辑 if __name__ == "__main__": # 示例:调用查看文档 # view_document("12345") # 如果是GUI程序,这里启动主循环 pass
关键说明
sys.frozen是PyInstaller编译后添加的标识,用来区分脚本运行和编译后的状态,确保正确获取自身可执行文件名称。file.name.isdigit()直接判断无扩展名的文件名是否全为数字,符合你存储文件的命名规则。- 加入异常处理避免因文件被占用等情况导致程序退出失败。
内容的提问来源于stack exchange,提问作者Martin Jeaks
相关产品推荐
相关产品推荐

