脚本 | 利用python自动整理桌面文件

鉴于自己的桌面实在太乱了,所以写了个python脚本自动整理无用文件。

我将脚本统一放在了桌面内的 script 文件夹内,同时在桌面建立了批处理文件archive_files.bat方便操作:

1
2
3
4
cd ./script
python archive_files.py "C:\\Users\\acezj\\Desktop"
pause
exit

脚本运行需要python环境

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# python
# archive_files.py
file_doc = [".doc", ".pptx", ".pdf", ".md", ".html"]
# 文档 => Doc
file_pic = [".jpg"]
# 图片 => Pic
file_tmp = [".torrent"]
# 其他 => Tmp
file_no_move = [".py", ".exe", ".bat",     
                 # 可执行文件(不移动)
                 ".lnk",                    
                 # 图标(不移动)
                 ".ini", ".drivedownload", ""
                 # 不移动
                ]
file_type_recognized = file_doc + file_pic + file_tmp + file_no_move
extension_not_exist = []
old_path, new_path = "", ""

def archive_files(file_dir):
    import os
    import shutil
    def getPath(file_dir, file, folder):
        old_path = os.path.join(file_dir, file)
        new_path = os.path.join(os.path.join(file_dir, folder), file)
        return old_path, new_path
    for file in os.listdir(file_dir):
        path = os.path.join(file_dir, file)
        extension = os.path.splitext(file)[1] 
        # 其中os.path.splitext()函数将路径拆分为文件名+扩展名
        if extension in file_doc:
            old_path, new_path = getPath(file_dir, file, "doc")
        elif extension in file_pic:
            old_path, new_path = getPath(file_dir, file, "pic")
        elif extension in file_tmp:
            old_path, new_path = getPath(file_dir, file, "tmp")
        elif extension in file_no_move:
            continue
        elif extension not in extension_not_exist:
            extension_not_exist.append(extension)
            continue
        shutil.move(old_path, new_path)
        print("unrecognized:", extension_not_exist)

# file_dir = "C:\\Users\\acezj\\Desktop"
import sys
file_dir = sys.argv[1]
archive_files(file_dir)

.bat批处理文件同级的 doc, pic, tmp 三个目录需要手动创建

会自动将设置好的后缀名文件移动至对应目录,同时没有处理过的文件后缀会列出

updatedupdated2023-01-302023-01-30
点击刷新