桌面清理器开源项目教程
desktop_cleaner项目地址:https://gitcode.com/gh_mirrors/de/desktop_cleaner
项目目录结构及介绍
桌面清理器项目的目录结构如下:
desktop_cleaner/
├── README.md
├── cleaner.py
├── config.json
└── test/
└── test_cleaner.py
README.md: 项目说明文档。cleaner.py: 项目的主启动文件。config.json: 项目的配置文件。test/: 测试文件夹,包含测试脚本 test_cleaner.py。项目的启动文件介绍
cleaner.py 是项目的启动文件,主要功能是清理桌面上的文件。以下是该文件的主要代码结构:
import os
import json
def load_config():
with open('config.json', 'r') as f:
config = json.load(f)
return config
def clean_desktop(config):
desktop_path = os.path.expanduser("~/Desktop")
for file_name in os.listdir(desktop_path):
file_path = os.path.join(desktop_path, file_name)
if os.path.isfile(file_path):
for folder, extensions in config.items():
if any(file_name.endswith(ext) for ext in extensions):
os.makedirs(os.path.join(desktop_path, folder), exist_ok=True)
os.rename(file_path, os.path.join(desktop_path, folder, file_name))
break
if __name__ == "__main__":
config = load_config()
clean_desktop(config)
load_config(): 加载配置文件 config.json。clean_desktop(config): 根据配置文件清理桌面文件。项目的配置文件介绍
config.json 是项目的配置文件,用于指定桌面文件的分类规则。以下是一个示例配置:
{
"Documents": [".doc", ".docx", ".pdf"],
"Images": [".jpg", ".png", ".gif"],
"Videos": [".mp4", ".avi", ".mkv"],
"Music": [".mp3", ".wav"],
"Others": []
}
Documents: 文档文件类型。Images: 图片文件类型。Videos: 视频文件类型。Music: 音乐文件类型。Others: 其他未分类文件类型。通过修改 config.json 文件,可以自定义桌面文件的分类规则。
desktop_cleaner项目地址:https://gitcode.com/gh_mirrors/de/desktop_cleaner