Py学习  »  Python

❤️女朋友桌面文件杂乱无章?气得我用Python给她做了一个文件整理工具❤️

Dream丶Killer • 2 年前 • 263 次点击  

先看效果图
请添加图片描述

写在前面

事情是这样子的,昨天回去无意看了一下女朋友桌面,密密麻麻的全是文件,各式各样的占满屏幕,简直要把我这个强迫症给难受死,让她整理一下,还懒的整理。
在这里插入图片描述
于是中午没休息写了一个文件整理工具给这个懒猪,希望她能够识抬举,给我点奖励~哈哈
废话不多说,进入正题!

主要涉及到的库:
tkinter :实现 GUI 编程(文本框、按钮、标签等组件实现 GUI 开发)。
pathlib :面向对象的编程方式来表示文件系统路径。
ttkthemes tkinter 主题包,让你的组件外观更加骚。
Pyinstaller :是一个非常简单的打包 .py 文件的库。


文件整理功能

本文实现的文件整理实际是一种文件分类的功能,将指定文件夹下的文件进行分类,并移动到该类别的文件夹下。

首先需要定义一个文件类型的字典,来指定每个类别文件有哪些。

FILE_TYPE = {
    "图片": [".jpeg", ".jpg", ".tiff", ".gif", ".bmp", ".png", ".bpg", "svg",
               ".heif", ".psd", ".raw"],
    "视频": [".avi", ".flv", ".wmv", ".mov", ".mp4", ".webm", ".vob", ".mng",
               ".qt", ".mpg", ".mpeg", ".3gp", ".mkv"],
    "文档": [".oxps", ".epub", ".pages", ".docx", ".doc", ".fdf", ".ods",
                  ".odt", ".pwi", ".xsn", ".xps", ".dotx", ".docm", ".dox",
                  ".rvg", ".rtf", ".rtfd", ".wpd", ".xls", ".xlsx", ".ppt",
                  "pptx",".csv",",pdf", ],
    "压缩文件": [".a", ".ar", ".cpio", ".iso", ".tar", ".gz", ".rz", ".7z",
                 ".dmg", ".rar"


    
, ".xar", ".zip"],
    "影音": [".aac", ".aa", ".aac", ".dvf", ".m4a", ".m4b", ".m4p", ".mp3",
              ".msv", ".ogg", ".oga", ".raw", ".vox", ".wav", ".wma"],
    "编程": [".py",".html5", ".html", ".htm", ".xhtml",".c",".cpp",".java",".css", ".ipynb", ".h", '.class'],
    "可执行程序": [".exe"],
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

整体代码的逻辑十分简单:遍历指定文件夹下的文件,忽略文件夹,只获取文件,判断文件类型是否在文件夹中出现,如果出现则移动到指定文件夹中(不存在文件夹则创建),否则归类到其他文件中。

from pathlib import Path

dir_path = r'C:\Users\pc\Desktop\test'
# 遍历指定文件夹下的文件,忽略文件夹
for file_path in Path(dir_path).glob('*.*'):
    temp = 0  # 标志是否已经通过FILE_TYPE分类
    for key, value in FILE_TYPE.items():
        if file_path.suffix in value:
            sub_dir = Path(dir_path, key)  # 某类文件夹路径
            if not sub_dir.exists():
                sub_dir.mkdir(exist_ok=True)  # 创建文件夹
            file_path.rename(Path(sub_dir, file_path.name))  # 移动文件
            temp = 1
            break
    if temp == 0:
        sub_dir = Path(dir_path, '其他文件')
        if not sub_dir.exists():
            sub_dir.mkdir(exist_ok=True)  # 创建保存没有被识别文件的文件夹
        file_path.rename(Path(sub_dir, file_path.name))  # 移动文件
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

实现 GUI 界面

实现 GUI 界面时在原有功能上添加了一个还原按钮,能够撤销文件整理的操作。

设置界面主题样式

window = ThemedTk(theme="adapta", fonts=True, themebg=True)
  • 1
  • 1

自定义 Label 样式

label_style = ttk.Style()
label_style.configure("Label", font=("微软雅黑", 22, 'bold'), foreground="red", background="yellow")
  • 1
  • 2
  • 1
  • 2

添加 Label 标签,并使用自定义的样式

# 添加标签
label = tk.Label(window, text='♥向日葵的专属 sun♥', style='Label')
  • 1
  • 2
  • 1
  • 2

在这里插入图片描述

添加选择路径组件及功能实现

# 设置选择路径组件
path = tk.StringVar()
entry = ttk.Entry(window, textvariable=path, width=30)
button1 = ttk.Button(window,width=10, text = "选择路径", command = selectPath)
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

点击 “选择路径” 按钮,执行 selectPath() 函数,将选择的文件夹路径传递给 entry 来显示在界面上

def selectPath():
    global dir_path
    # 选择文件path接收文件地址
    dir_path = filedialog.askdirectory(title='选择待整理的文件夹')
    # 通过replace函数替换绝对文件地址中的/来使文件可被程序读取
    dir_path.replace("/", r"\\")
    path.set(dir_path)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

在这里插入图片描述

添加“整理”,“撤销”组件及功能实现

# 添加“整理”按钮
button2 = ttk.Button(window,width=10, text = "整理", command = organize_files)
# 添加“还原”按钮
button3 = ttk.Button(window,width=10, text = "还原", command = cancle_organize)
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

点击“整理”按钮,执行 organize_files() 函数,实现文件整理,并记录文件 原路径 新路径 ,同时也要记录新创建的文件夹路径,因为还原操作时要将新创建的文件夹进行删除。

def organize_files():
    if dir_path == '':
        tree.heading("#0", text="还未选取路径哦")
        return None
    global organize_temp
    organize_temp = 1
    # 遍历指定文件夹下的文件,忽略文件夹
    for file_path in Path(dir_path).glob('*.*'):
        temp = 0  # 标志是否已经通过FILE_TYPE继续分类
        for key, value in FILE_TYPE.items():
            if file_path.suffix in value:
                sub_dir = Path(dir_path, key)  # 某类文件夹路径
                if not sub_dir.exists():
                    sub_dir.mkdir(exist_ok=True)  # 创建文件夹
                    create_dir_path.append(sub_dir)
                file_path.rename(Path(sub_dir, file_path.name))  # 移动文件
                old_file_path[Path(sub_dir, file_path.name)] = file_path
                temp = 1
                break
        if temp == 0:
            sub_dir = Path(dir_path, '其他文件')
            if not sub_dir.exists():
                sub_dir.mkdir(exist_ok=True)  # 创建保存没有被识别文件的文件夹
                create_dir_path.append(sub_dir)
            file_path.rename(Path(sub_dir, file_path.name))  # 移动文件
            old_file_path[Path(sub_dir, file_path.name)] = file_path
        tree.heading("#0", text="整理完成")
  • 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
  • 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

点击“还原”按钮,执行 cancle_organize() 函数,还原文件至整理之前

def cancle_organize():
    if organize_temp == 0:
        tree.heading("#0", text="还未整理哦")
        return None
    for new_path, old_path in old_file_path.items():
        new_path.rename(old_path)  # 还原文件
    for dir_path in create_dir_path:
        dir_path.rmdir()  # 不能使用unlink()来删除,报错无权限
    tree.heading("#0", text="还原成功")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

添加输出框显示运行后的信息

# 添加输出框显示
tree = ttk.Treeview(height=1, show=("tree", "headings"))
  • 1
  • 2
  • 1
  • 2

设置各个组件在界面的位置

# 设置组件位置
label.grid(row=0, column=0, padx=20, pady=40)
entry.grid(row = 3, column = 0, pady=5)
button1.grid(row = 3, column = 1, padx=20)
button2.grid(row = 4, column = 0, pady=5)
button3.grid(row = 5, column = 0, pady=5)
tree.grid(row=6, column=0,


    
 pady=5)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

至此,一个文件整理的小工具就已经实现了。整体界面如下:
在这里插入图片描述


源码打包

首先要确保已经安装 pyinstaller ,没有安装的可以先安装一下。

pip install -i https://pypi.douban.com/simple pyinstaller 
  • 1
  • 1

pyinstaller 使用时的常用参数含义:

-F :打包单个文件,产生一个文件用于部署(默认),如果代码都写在一个 .py 文件时使用,项目有多个文件时不要使用

pyinstaller -F xxx.py
  • 1
  • 1

-D :打包多个文件,产生一个目录用于部署(默认),用于框架编写的代码打包

pyinstaller -D xxx.py(项目入口文件)
  • 1
  • 1

–key=keys :使用 keys 进行加密打包

pyinstaller --key=123456 -F xxx.py
  • 1
  • 1

-d :产生 debug 版本的可执行文件

-p :用来添加程序所用到的包的所在位置,设置导入路径,可以用 ; ( Linux 使用 : )分割来指定多个目录。

-w :表示不用控制台窗口,使用 Windows 子系统执行,当程序启动的时候不会打开命令行(只对 Windows 有效)

-c :表示打开控制台窗口,使用控制台子系统执行,当程序启动的时候会打开命令行(默认)(只对 Windows 有效)

-i :将 file.ico 添加为可执行文件的资源,改变程序的图标(只对 Windows 系统有效)

安装完成后,新建一个文件夹,将源文件放到该文件夹下面,打开 cmd cd 进入该文件夹下 (重点),执行下面语句
在这里插入图片描述

生成的文件结构如下

exe 可执行文件在 dist 目录下
在这里插入图片描述
到这里就可以把 .exe 文件发送别人了,并且可以在没有任何配置的情况下运行哦~(前提是同样是 Windows 下)

这里的图标是我自己在网上找的。

如果没有 ico 格式的图标的话,

推荐一个免费的 icon 网站: https://iconstore.co/

然后在 https://www.aconvert.com/cn/icon/svg-to-ico/ 转换成指定大小的 ico 图标。

最后文章中的源码及打包后的文件已经放到链接下,需要的可以自己下载。 粉丝可以直接私信我个邮箱直接发送到位哦 ~
代码获取: https://download.csdn.net/download/qq_43965708/21539497


晚上去找女朋友领奖励~
在这里插入图片描述

这就是本文所有的内容了,如果感觉还不错的话。 ❤ 点个赞再走吧!!!❤

在这里插入图片描述
后续会继续分享各种有趣的文章,如果感兴趣的话可以点个关注不迷路哦~。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/119104
 
263 次点击