You've successfully subscribed to The Daily Awesome
Great! Next, complete checkout for full access to The Daily Awesome
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info is updated.
Billing info update failed.
脚本 | 利用python自动整理桌面文件

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

. 1 min read

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

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

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

脚本运行需要python环境

# 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 三个目录需要手动创建

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