網(wǎng)站首頁 編程語言 正文
前言:
平時(shí)工作沒有養(yǎng)成分類的習(xí)慣,整個(gè)桌面雜亂無章都是文檔和資料,幾乎快占滿整個(gè)屏幕了。所以必須要整理一下了,今天我們來看下用python如何批量將不同后綴的文件移動(dòng)到同一文件夾。
演示效果:
- 使用前
- 使用后
代碼:
# # -*- coding:utf-8 -*- import os import glob import shutil import tkinter import tkinter.filedialog from datetime import datetime def start(): ? ? root = tkinter.Tk() ? ? root.withdraw() ? ? dirname = tkinter.filedialog.askdirectory(parent=root,initialdir="/",title='請選擇文件夾') ? ? return dirname # 定義一個(gè)文件字典,不同的文件類型,屬于不同的文件夾 file_dict = { ? ? "圖片": ["jpeg", "jpg", "tiff", "gif", "bmp", "png", "bpg", "svg", "heif", "psd"], ? ? "視頻": ["avi", "flv", "wmv", "mov", "mp4", "webm", "vob", "mng", "qt", "mpg", "mpeg", "3gp", "mkv"], ? ? "音頻": ["aac", "aa", "aac", "dvf", "m4a", "m4b", "m4p", "mp3", "msv", "ogg", "oga", "raw", "vox", "wav", "wma"], ? ? "文檔": ["oxps", "epub", "pages", "docx", "doc", "fdf", "ods", "odt", "pwi", "xsn", "xps", "dotx", "docm", "dox", "rvg", "rtf", "rtfd", "wpd", "xls", "xlsx","xlsm","ppt", "pptx", "csv", "pdf", "md","xmind"], ? ? "壓縮文件": ["a", "ar", "cpio", "iso", "tar", "gz", "rz", "7z", "dmg", "rar", "xar", "zip"], ? ? "文本": ["txt", "in", "out","json","xml","log"], ? ? "程序腳本": ["py", "html5", "html", "htm", "xhtml", "cpp", "java", "css","sql"],? ? ? '可執(zhí)行程序': ['exe', 'bat', 'lnk', 'sys', 'com','apk'], ? ? '字體文件': ['eot', 'otf', 'fon', 'font', 'ttf', 'ttc', 'woff', 'woff2','shx'], ? ? '工程圖文件':['bak','dwg','dxf','dwl','dwl2','stp','SLDPRT','ipj','ipt','idw'] } # 定義一個(gè)函數(shù),傳入每個(gè)文件對應(yīng)的后綴。判斷文件是否存在于字典file_dict中; # 如果存在,返回對應(yīng)的文件夾名;如果不存在,將該文件夾命名為"未知分類"; def JudgeFile(suffix): ? ? for name, type_list in file_dict.items(): ? ? ? ? if suffix.lower() in type_list: ? ? ? ? ? ? return name ? ? return "未知分類" if __name__ == '__main__': ? ? try: ? ? ? ? while True: ? ? ? ? ? ? path = start() ? ? ? ? ? ? print("---->路徑是: ",path) ? ? ? ? ? ? if path == "": ? ? ? ? ? ? ? ? print("沒有選擇路徑!") ? ? ? ? ? ? ? ? break ? ? ? ? ? ? # 遞歸獲取 "待處理文件路徑" 下的所有文件和文件夾。 ? ? ? ? ? ? startTime = datetime.now().second ? ? ? ? ? ? for file in glob.glob(f"{path}/**/*", recursive=True): ? ? ? ? ? ? ? ? # 由于我們是對文件分類,這里需要挑選出文件來。 ? ? ? ? ? ? ? ? if os.path.isfile(file): ? ? ? ? ? ? ? ? ? ? # 由于isfile()函數(shù),獲取的是每個(gè)文件的全路徑。這里再調(diào)用basename()函數(shù),直接獲取文件名; ? ? ? ? ? ? ? ? ? ? file_name = os.path.basename(file) ? ? ? ? ? ? ? ? ? ? suffix = file_name.split(".")[-1] ? ? ? ? ? ? ? ? ? ? # 判斷 "文件名" 是否在字典中。 ? ? ? ? ? ? ? ? ? ? name = JudgeFile(suffix) ? ? ? ? ? ? ? ? ? ? # 根據(jù)每個(gè)文件分類,創(chuàng)建各自對應(yīng)的文件夾。 ? ? ? ? ? ? ? ? ? ? if not os.path.exists(f"{path}\\{name}"): ? ? ? ? ? ? ? ? ? ? ? ? os.mkdir(f"{path}\\{name}") ? ? ? ? ? ? ? ? ? ? ? ? print('path-->',name) ? ? ? ? ? ? ? ? ? ? # 將文件復(fù)制到各自對應(yīng)的文件夾中。 ? ? ? ? ? ? ? ? ? ? # shutil.copy(file, f"{path}\\{name}") ? ? ? ? ? ? ? ? ? ? # 將文件移動(dòng)到各自對應(yīng)的文件夾中。 ? ? ? ? ? ? ? ? ? ? shutil.move(file, f"{path}\\{name}") ? ? ? ? ? ? endTime = datetime.now().second ? ? ? ? ? ? countTime= endTime-startTime ? ? ? ? ? ? print("---->已經(jīng)整理完成。共花費(fèi) {} s".format(countTime)) ? ? ? ? ? ? a = input('---->請按回車鍵退出:') ? ? ? ? ? ? if a == '': ? ? ? ? ? ? ? ? break ? ? except BaseException: ? ? ? ? print('存在重復(fù)的文件!')
執(zhí)行起來很簡單,只要寫完程序,點(diǎn)擊程運(yùn)行,等待彈出窗口,選擇需要整理的文件夾即可。
如果覺得以上代碼覺得復(fù)雜,可以嘗試以下更為簡單的程序。
如何實(shí)現(xiàn)文件自動(dòng)分類?
同一目錄下存在很多不同類型的資源條件
- 1 .分類
- 2.創(chuàng)建分類目錄
- 3.移動(dòng)文件資源
import os import shutil import tkinter import tkinter.filedialog from datetime import datetime def start(): ? ? root = tkinter.Tk() ? ? root.withdraw() ? ? dirname = tkinter.filedialog.askdirectory(parent=root,initialdir="/",title='請選擇文件夾') ? ? return dirname # 源文件存在路徑 src_dir=start() # 分類資源存在路徑 dest_dir=src_dir # 判斷目錄是否存在 if not os.path.exists(dest_dir): ? ? os.mkdir(dest_dir) # 源目錄分析 files=os.listdir(src_dir) for item in files: ? ? src_path=os.path.join(src_dir,item) ? ? # 判斷狀態(tài) ? ? if os.path.isfile(src_path): ? ? ? ? #如果是文件,進(jìn)入代碼塊 ? ? ? ? # 判斷文件資源的類型 ? ? ? ? ndir = item.split('.')[-1] ? ? ? ? desc_path=os.path.join(dest_dir,ndir) ? ? ? ? # 創(chuàng)建分類目錄 ? ? ? ? if not os.path.exists(desc_path): ? ? ? ? ? ? # 如果分類子目錄不存在,創(chuàng)建 ? ? ? ? ? ? os.mkdir(desc_path) ? ? ? ? shutil.move(src_path,desc_path)
原文鏈接:https://blog.csdn.net/weixin_42750611/article/details/124051648
相關(guān)推薦
- 2022-07-15 C#中Timer定時(shí)器類的簡單使用_C#教程
- 2022-05-12 正則判斷只能輸入大于0的正整數(shù)
- 2022-03-15 BeanCreationException或NoSuchBeanDefinitionExceptio
- 2022-10-17 python?文件讀寫和數(shù)據(jù)清洗_python
- 2022-10-28 Go語言包和包管理詳解_Golang
- 2022-05-23 iOS實(shí)現(xiàn)無限滑動(dòng)效果_IOS
- 2022-10-02 react中的useImperativeHandle()和forwardRef()用法_React
- 2022-09-08 pandas實(shí)現(xiàn)datetime64與unix時(shí)間戳互轉(zhuǎn)_python
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支