700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > Python一键自动整理归类文件 GUI窗口程序拿来即用

Python一键自动整理归类文件 GUI窗口程序拿来即用

时间:2023-03-14 20:56:09

相关推荐

Python一键自动整理归类文件 GUI窗口程序拿来即用

应黄同学《用Python写了个小工具,再复杂的文件夹,分分钟帮你整理,拿来即用!》一文的邀请,谁写个gui并给他投稿就送书。

那么我考虑大家的需要,结合实际,按照自己的思路写下了这个小工具:

选择目录后,就可以进行整理了,下面是整理前后的效果:

看提示可以知道还支持回退。

点击回退就可以回到之前的状态并所有删除空文件夹。

根据实际需求,需要被整理的文件夹往往都是单层的,例如桌面的,所以程序并不支持去对子文件夹去递归处理。已经在子文件夹中的文件都会被认为是已经被整理过了。

使用效果:

若你想定制分类配置,只需要修改同一目录下的config.json配置文件就行了:

点击重载配置即可在不重启程序的情况下生效。也可以直接通过程序本身提供的编辑框修改配置,点击保存修改即可。

那么,这个工具到底是如何开发出来的呢?

开发流程

核心逻辑开发

首先定义分类字典:

file_dict = {'图片': ["jpeg", 'jpg', 'png', 'gif', 'webp', "bmp", "bpg", "svg", "heif", "psd"],'视频': ['rmvb', 'mp4', 'avi', 'mkv', 'flv', "wmv", "mov", "mpg", "mpeg", "3gp"],"音频": ['m4a', 'aac', 'ogg', 'oga', 'mp3', 'wma', "wav"],"电子书": ['pdf', "epub", "mobi", "azw3", "chm", "txt"],"数据与表格": ['xls', 'xlsx', "xlsm", 'csv', 'json', 'xml'],"文档": ['doc', 'docx', 'ppt', 'pptx', 'md', ".txt"],"思维导图": ["emmx", "mmap", "xmind"],'程序脚本': ['py', 'java', 'html', 'sql', 'r', 'css', 'cpp', 'c', 'js', 'go'],'压缩文件': ["tar", "gz", "rz", "7z", "dmg", "rar", "xar", "zip", "iso"],'可执行程序': ['exe', 'bat', 'sys', 'com'],'字体文件': ['eot', 'otf', 'fon', 'font', 'ttf', 'ttc', 'woff', 'woff2']}

然后定义一个函数用于获取一个文件属于的类型:

def get_file_type(filename):"传入文件名,读取file_dict配置,根据后缀判断文件类型"for file_type, suffixs in file_dict.items():for suffix in suffixs:if filename.endswith("."+suffix.lstrip(".")):return file_typereturn "未知类型"

调用方式:

get_file_type(r"D:\360安全浏览器下载\document.pdf")

'电子书'

下面使用pathlib库保存移动信息:

from pathlib import Pathdef mkdirAndGetChange(path):path = Path(path)result = []for file in path.glob("*"):if file.is_dir():continuesrc_path = file.absolute()dest_dir = get_file_type(file.name)dest_path = path/dest_dir/file.namedest_dir = dest_path.parentif not dest_dir.exists():dest_dir.mkdir()result.append((src_path, dest_path))return result

调用方式:

path = r"D:\360安全浏览器下载"file_changes = mkdirAndGetChange(path)print(file_changes)

[(WindowsPath('D:/360安全浏览器下载/9种常用的数据分析方法.pdf'),WindowsPath('D:/360安全浏览器下载/电子书/9种常用的数据分析方法.pdf')),...(WindowsPath('D:/360安全浏览器下载/金融时间序列分析讲义.pdf'),WindowsPath('D:/360安全浏览器下载/电子书/金融时间序列分析讲义.pdf'))]

然后需要改名时:

for src_path, dest_path in file_changes:src_path.rename(dest_path)

还可以再还原回来:

for src_path, dest_path in file_changes:dest_path.rename(src_path)

最后写一个方法用于清空空白文件夹:

def clear_black_dir(path):path = Path(path)for file in path.glob("*"):if not file.is_dir():continueif not os.listdir(file):file.rmdir()path = r"D:\360安全浏览器下载"clear_black_dir(path)

GUI开发

为了方便修改配置,将配置文件写到单独的文件中。在封装上述核心逻辑,命名为auto_organize.py

内容如下:

"""小小明的代码CSDN主页:/as604049322"""__author__ = '小小明'__time__ = '/8/11'import jsonimport osfrom pathlib import Pathdef load_config_json():with open("config.json", encoding="u8") as f:config_json = f.read()return config_jsondef save_config(config):with open("config.json", "w", encoding="u8") as f:f.write(config)config_json = load_config_json()file_dict = json.loads(config_json)def get_file_type(filename):"传入文件名,读取file_dict配置,根据后缀判断文件类型"for file_type, suffixs in file_dict.items():for suffix in suffixs:if filename.endswith("." + suffix.lstrip(".")):return file_typereturn "未知类型"def mkdirAndGetChange(path):path = Path(path)result = []for file in path.glob("*"):if file.is_dir():continuesrc_path = file.absolute()dest_dir = get_file_type(file.name)dest_path = path / dest_dir / file.namedest_dir = dest_path.parentif not dest_dir.exists():dest_dir.mkdir()result.append((src_path, dest_path))return resultdef clear_black_dir(path):path = Path(path)num = 0for file in path.glob("*"):if not file.is_dir():continueif not os.listdir(file):file.rmdir()num += 1return num

配置文件config.json的内容是:

{"图片": ["jpeg", "jpg", "png", "gif", "webp", "bmp", "bpg", "svg", "heif", "psd"],"视频": ["rmvb", "mp4", "avi", "mkv", "flv", "wmv", "mov", "mpg", "mpeg", "3gp"],"音频": ["m4a", "aac", "ogg", "oga", "mp3", "wma", "wav"],"电子书": ["pdf", "epub", "mobi", "azw3", "chm", "txt"],"数据与表格": ["xls", "xlsx", "xlsm", "csv", "json", "xml"],"文档": ["doc", "docx", "ppt", "pptx", "md", ".txt"],"思维导图": ["emmx", "mmap", "xmind"],"程序脚本": ["py", "java", "html", "sql", "r", "css", "cpp", "c", "js", "go"],"压缩文件": ["tar", "gz", "rz", "7z", "dmg", "rar", "xar", "zip", "iso"],"可执行程序": ["exe", "bat", "sys", "com"],"字体文件": ["eot", "otf", "fon", "font", "ttf", "ttc", "woff", "woff2"]}

GUI程序开发代码:

"""小小明的代码CSDN主页:/as604049322"""__author__ = '小小明'__time__ = '/8/11'import jsonimport osimport sysimport PySimpleGUI as sgimport auto_organizesg.change_look_and_feel("LightBlue")layout = [[sg.Text("被处理的文件夹路径(默认为当前路径):")],[sg.In(key="path"),sg.FolderBrowse('...', target='path')],[sg.Button('开始整理', enable_events=True, key="auto_organize", font=('楷体', 15)),sg.Button('回退', enable_events=True, key="back_before", pad=(20, 0), font=('楷体', 15)),sg.Button('删除空文件夹', enable_events=True, key="del_black", pad=(10, 0), font=('楷体', 15))],[sg.Text("改名配置:"),sg.Button('重载配置', enable_events=True, key="reload_config"),sg.Button('保存修改', enable_events=True, key="save_config")],[sg.Multiline(size=(46, 12), key="out")],[sg.Text("@小小明:/as604049322"), ],]def resource_path(relative_path):base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))return os.path.join(base_path, relative_path)window = sg.Window('文件夹整理工具 by 小小明', layout, icon=resource_path("h.ico"))window.finalize()window["out"].update(auto_organize.config_json)file_changes = Nonewhile True:event, values = window.read()# print(event, values)if event in (None,):break # 相当于关闭界面elif event == "auto_organize":path = values['path']if os.path.abspath(path) == os.path.abspath("."):sg.popup("未选择路径或输入的路径为当前目录,\n不允许选择程序所在的路径!", title="提示")continuefile_changes = auto_organize.mkdirAndGetChange(path)for src_path, dest_path in file_changes:src_path.rename(dest_path)sg.popup("整理完成,允许一次回退重置!", title="提示")elif event == "back_before":if not file_changes:sg.popup("未执行过整理操作!", title="提示")continuefor src_path, dest_path in file_changes:dest_path.rename(src_path)auto_organize.clear_black_dir(values['path'])file_changes = Nonesg.popup("回退完成并删除了全部的空文件夹!", title="提示")elif event == "del_black":n = auto_organize.clear_black_dir(values['path'])sg.popup(f"共删除了{n}个空文件夹!", title="提示")elif event == "reload_config":auto_organize.config_json = auto_organize.load_config_json()auto_organize.file_dict = json.loads(auto_organize.config_json)window["out"].update(auto_organize.config_json)elif event == "save_config":auto_organize.save_config(values["out"])

exe打包

这里我使用的打包命令是:

pyinstaller -Fw --icon=h.ico auto_organize_gui.py --add-data="h.ico;/"

h.ico是程序的图标文件。

打包完成后,我们就可以愉快的使用我们的小工具啦。

相关问题解答

关于图标资源打包的问题

这次在我使用PySimpleGUI开发中,与以往的主要区别是给程序主界面增加了图标,这个使用window窗口函数的第三个参数传入图标路径即可实现,示例:

sg.Window('PySimpleGUI',layout,icon='ico.ico')

但是问题来了,如何将图标文件打包到exe中并能够顺利被程序读取到呢?

当然解决这个问题另一个麻烦的方法是,是将图标的base64编码硬写到代码中再程序解码,显然这种方案并不太好,修改图标不方便。

如果最终将所有文件到打包到一个exe时,运行环境就会有所变化,运行时会临时进行解压,解压的目录为:C:\Users\用户名\AppData\Local\Temp\随机目录名,sys._MEIPASS则存储这个目录的位置。我们可以根据sys模块是否存在_MEIPASS属性来判断是直接运行,还是解压到临时目录再运行。最终定义了如下方法:

def resource_path(relative_path):base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))return os.path.join(base_path, relative_path)

打包时使用了–add-data参数,添加用;分隔的两个路径。--add-data="h.ico;/"表示将h.ico文件打包进去,运行时解压到根目录下。

如何制作ico图标

使用ico生成的在线网站使用本地软件imagine另存图片为ico使用python库PythonMagick

第一种方法任何人都可以直接用,百度一下,一大堆相关的网站。第二种方法该软件可以通过百度Imagine 看图软件下载到。

可惜PythonMagick库并不是可以直接使用pip进行安装。

需要到https://www.lfd.uci.edu/~gohlke/pythonlibs/#pythonmagick下载对应自己的python版本。

下载后直接安装whl文件,例如:

pip install PythonMagick-0.9.19-cp37-cp37m-win_amd64.whl

在代码中的调用示例为:

import PythonMagickimg = PythonMagick.Image("D:\h.jpg")img.sample('128x128')img.write('h.ico')

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。