文件夾太亂?Python小程序瞬間幫你整理到位
糟透了
一鍵整理桌面的軟件很多,但是對于其他路徑下的文件,我同樣需要整理,于是我想到使用Python,完成這個需求。
效果展示
圖片、視頻、音頻、文檔、壓縮文件、常用格式、程序腳本、可執(zhí)行程序和字體文件。# 不同文件組成的嵌套字典
file_dict = {
'圖片': ['jpg','png','gif','webp'],
'視頻': ['rmvb','mp4','avi','mkv','flv'],
"音頻": ['cd','wave','aiff','mpeg','mp3','mpeg-4'],
'文檔': ['xls','xlsx','csv','doc','docx','ppt','pptx','pdf','txt'],
'壓縮文件': ['7z','ace','bz','jar','rar','tar','zip','gz'],
'常用格式': ['json','xml','md','ximd'],
'程序腳本': ['py','java','html','sql','r','css','cpp','c','sas','js','go'],
'可執(zhí)行程序': ['exe','bat','lnk','sys','com'],
'字體文件': ['eot','otf','fon','font','ttf','ttc','woff','woff2']
}
常用格式需要為大家解釋一下,對于平時經(jīng)常使用,但是又不知道放在哪一類的文件,都存放在這里。開發(fā)思路
os模塊、shutil模塊、glob模塊,它們搭配使用,用來處理文件和文件夾,簡直超給力!① 任意給定一個文件路徑; ② 獲取當(dāng)前文件路徑下的所有文件,并取得每個文件對應(yīng)的后綴; ③ 判斷每個文件,是否在指定的嵌套字典中,并返回對應(yīng)的文件分類; ④ 判斷每個文件分類的文件夾是否存在。因為需要創(chuàng)建新的文件夾,用于分類存放文件; ⑤ 將每個文件,復(fù)制到對應(yīng)的分類中;
# 導(dǎo)入相關(guān)庫
import os
import glob
import shutil
# 采用input()函數(shù),動態(tài)輸入要處理的文件路徑。
path = input("請輸入要清理的文件路徑:")
# 定義一個文件字典,不同的文件類型,屬于不同的文件夾,一共9個大類。
file_dict = {
'圖片': ['jpg','png','gif','webp'],
'視頻': ['rmvb','mp4','avi','mkv','flv'],
"音頻": ['cd','wave','aiff','mpeg','mp3','mpeg-4'],
'文檔': ['xls','xlsx','csv','doc','docx','ppt','pptx','pdf','txt'],
'壓縮文件': ['7z','ace','bz','jar','rar','tar','zip','gz'],
'常用格式': ['json','xml','md','ximd'],
'程序腳本': ['py','java','html','sql','r','css','cpp','c','sas','js','go'],
'可執(zhí)行程序': ['exe','bat','lnk','sys','com'],
'字體文件': ['eot','otf','fon','font','ttf','ttc','woff','woff2']
}
# 定義一個函數(shù),傳入每個文件對應(yīng)的后綴。判斷文件是否存在于字典file_dict中;
# 如果存在,返回對應(yīng)的文件夾名;如果不存在,將該文件夾命名為"未知分類";
def func(suffix):
for name, type_list in file_dict.items():
if suffix.lower() in type_list:
return name
return "未知分類"
# 遞歸獲取 "待處理文件路徑" 下的所有文件和文件夾。
for file in glob.glob(f"{path}/**/*",recursive=True):
# 由于我們是對文件分類,這里需要挑選出文件來。
if os.path.isfile(file):
# 由于isfile()函數(shù),獲取的是每個文件的全路徑。這里再調(diào)用basename()函數(shù),直接獲取文件名;
file_name = os.path.basename(file)
suffix = file_name.split(".")[-1]
# 判斷 "文件名" 是否在字典中。
name = func(suffix)
#print(func(suffix))
# 根據(jù)每個文件分類,創(chuàng)建各自對應(yīng)的文件夾。
if not os.path.exists(f"{path}\\{name}"):
os.mkdir(f"{path}\\{name}")
# 將文件復(fù)制到各自對應(yīng)的文件夾中。
shutil.copy(file,f"{path}\\{name}")

窗口界面
可視化界面,也沒有將程序打包,所以我自己用沒問題,要是發(fā)給別人就不太好使了。小工具效果展示


開始整理,選擇待整理的文件夾后,就可以進(jìn)行整理了,下面是整理前后的效果圖。
回退功能和刪除空文件夾功能?;赝斯δ芫褪钱?dāng)你將文件夾整理完畢后,點擊回退,又可以恢復(fù)到文件夾原始模樣。私人定制,只需要去修改同一目錄下的config.json配置文件就行。
重載配置,即可在不重啟程序的情況下生效。也可以直接通過程序本身提供的編輯框修改配置,點擊保存修改即可。小工具功能開發(fā)流程
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"],
"數(shù)據(jù)與表格": ['xls', 'xlsx', "xlsm", 'csv', 'json', 'xml'],
"文檔": ['doc', 'docx', 'ppt', 'pptx', 'md', ".txt"],
"思維導(dǎo)圖": ["emmx", "mmap", "xmind"],
'程序腳本': ['py', 'java', 'html', 'sql', 'r', 'css', 'cpp', 'c', 'js', 'go'],
'壓縮文件': ["tar", "gz", "rz", "7z", "dmg", "rar", "xar", "zip", "iso"],
'可執(zhí)行程序': ['exe', 'bat', 'sys', 'com'],
'字體文件': ['eot', 'otf', 'fon', 'font', 'ttf', 'ttc', 'woff', 'woff2']
}
def get_file_type(filename):
"傳入文件名,讀取file_dict配置,根據(jù)后綴判斷文件類型"
for file_type, suffixs in file_dict.items():
for suffix in suffixs:
if filename.endswith("."+suffix.lstrip(".")):
return file_type
return "未知類型"
get_file_type(r"D:\360安全瀏覽器下載\document.pdf")
# 結(jié)果如下:電子書
from pathlib import Path
def mkdirAndGetChange(path):
path = Path(path)
result = []
for file in path.glob("*"):
if file.is_dir():
continue
src_path = file.absolute()
dest_dir = get_file_type(file.name)
dest_path = path/dest_dir/file.name
dest_dir = dest_path.parent
if 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種常用的數(shù)據(jù)分析方法.pdf'),
WindowsPath('D:/360安全瀏覽器下載/電子書/9種常用的數(shù)據(jù)分析方法.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():
continue
if not os.listdir(file):
file.rmdir()
path = r"D:\360安全瀏覽器下載"
clear_black_dir(path)
小工具GUI開發(fā)流程
"""python
小小明的代碼
CSDN主頁:https://blog.csdn.net/as604049322
"""
__author__ = '小小明'
__time__ = '2021/8/11'
import json
import os
from pathlib import Path
def load_config_json():
with open("config.json", encoding="u8") as f:
config_json = f.read()
return config_json
def 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配置,根據(jù)后綴判斷文件類型"
for file_type, suffixs in file_dict.items():
for suffix in suffixs:
if filename.endswith("." + suffix.lstrip(".")):
return file_type
return "未知類型"
def mkdirAndGetChange(path):
path = Path(path)
result = []
for file in path.glob("*"):
if file.is_dir():
continue
src_path = file.absolute()
dest_dir = get_file_type(file.name)
dest_path = path / dest_dir / file.name
dest_dir = dest_path.parent
if not dest_dir.exists():
dest_dir.mkdir()
result.append((src_path, dest_path))
return result
def clear_black_dir(path):
path = Path(path)
num = 0
for file in path.glob("*"):
if not file.is_dir():
continue
if not os.listdir(file):
file.rmdir()
num += 1
return num
{
"圖片": ["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"],
"數(shù)據(jù)與表格": ["xls", "xlsx", "xlsm", "csv", "json", "xml"],
"文檔": ["doc", "docx", "ppt", "pptx", "md", ".txt"],
"思維導(dǎo)圖": ["emmx", "mmap", "xmind"],
"程序腳本": ["py", "java", "html", "sql", "r", "css", "cpp", "c", "js", "go"],
"壓縮文件": ["tar", "gz", "rz", "7z", "dmg", "rar", "xar", "zip", "iso"],
"可執(zhí)行程序": ["exe", "bat", "sys", "com"],
"字體文件": ["eot", "otf", "fon", "font", "ttf", "ttc", "woff", "woff2"]
}
"""
小小明的代碼
CSDN主頁:https://blog.csdn.net/as604049322
"""
__author__ = '小小明'
__time__ = '2021/8/11'
import json
import os
import sys
import PySimpleGUI as sg
import auto_organize
sg.change_look_and_feel("LightBlue")
layout = [
[sg.Text("被處理的文件夾路徑(默認(rèn)為當(dāng)前路徑):")],
[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("@小小明:https://blog.csdn.net/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 = None
while True:
event, values = window.read()
# print(event, values)
if event in (None,):
break # 相當(dāng)于關(guān)閉界面
elif event == "auto_organize":
path = values['path']
if os.path.abspath(path) == os.path.abspath("."):
sg.popup("未選擇路徑或輸入的路徑為當(dāng)前目錄,\n不允許選擇程序所在的路徑!", title="提示")
continue
file_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("未執(zhí)行過整理操作!", title="提示")
continue
for src_path, dest_path in file_changes:
dest_path.rename(src_path)
auto_organize.clear_black_dir(values['path'])
file_changes = None
sg.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"])
程序打包
pyinstaller -Fw --icon=h.ico auto_organize_gui.py --add-data="h.ico;/"
h.ico是程序的圖標(biāo)文件。打包完成后,我們就可以愉快的使用我們的小工具啦。① 關(guān)于圖標(biāo)資源打包的問題
sg.Window('PySimpleGUI',layout,icon='ico.ico')
C:\Users\用戶名\AppData\Local\Temp\隨機(jī)目錄名,sys._MEIPASS則存儲這個目錄的位置。我們可以根據(jù)sys模塊是否存在_MEIPASS屬性來判斷是直接運(yùn)行,還是解壓到臨時目錄再運(yùn)行。最終定義了如下方法: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參數(shù),添加用 ; 分隔的兩個路徑。--add-data="h.ico;/"表示將h.ico文件打包進(jìn)去,運(yùn)行時解壓到根目錄下。② 如何制作ico圖標(biāo)
使用ico生成的在線網(wǎng)站; 使用本地軟件imagine另存圖片為ico; 使用python庫PythonMagick;
pip install PythonMagick-0.9.19-cp37-cp37m-win_amd64.whl
import PythonMagick
img = PythonMagick.Image("D:\h.jpg")
img.sample('128x128')
img.write('h.ico')
作者:黃偉呢、小小明
_往期文章推薦_
評論
圖片
表情
