python中文件分类_python实现根据文件格式分类
本文實例為大家分享了python根據文件格式分類的具體代碼,供大家參考,具體內容如下
使用到python內置os模塊(對目錄或文件的新建/刪除/屬性查看,還提供了對文件以及目錄的路徑操作)、shutil模塊(高等級的目錄或文件的移動/復制/打包/壓縮/解壓等操作)
import os,shutil,time
def files_classfy(target_path):
global count #定義全局變量
file_list = os.listdir(target_path) #列出目標路徑下的所有文件列表
for file in file_list: #遍歷取到每一個文件名
os.chdir(target_path) #改變當前工作目錄為目標路徑
if file.find('.') == -1: #如果當前文件名中無擴展名則跳過
continue
filetype = file.split('.')[-1] #取得文件擴展名格式,windows下文件需設置為擴展名可見
if not os.path.exists(filetype):
os.mkdir(filetype) #如果工作目錄下不存在以當前擴展名命名的文件夾則創建該文件夾(默認屬性為0777)
new_path = os.path.join(target_path,'%s'%filetype) #取得當前擴展名文件夾路徑
os.chdir(new_path)
if os.path.exists(file): #如果當前擴展名文件夾中已存在同名文件則跳過
continue
else:
os.chdir(target_path) #將工作目錄切換回目標文件夾
shutil.move(file,filetype) #移動相同格式的文件到對應的格式文件夾
count+=1
start = time.time()
count = 0
path = "G:\picture\mi5splus"
files_classfy(path)
total_time = time.time() - start
print("程序運行時間:%0.2f"%total_time)
print("共處理圖片:%d"%count)
運行結果:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持我們。
本文標題: python實現根據文件格式分類
本文地址: http://www.cppcns.com/jiaoben/python/283399.html
總結
以上是生活随笔為你收集整理的python中文件分类_python实现根据文件格式分类的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: usb声卡驱动_来自MOTU的温馨提示:
- 下一篇: 可以治疗不育吗