python實現快速檔案格式批量轉換的方法
阿新 • • 發佈:2020-10-19
用python實現資料夾下的成批檔案格式轉換
我們對於檔案轉換的需求很大,甚至於對於圖片的格式,JPG和PNG格式在肉眼看來都沒什麼差別,但是對於計算機而言,它有時候就只接受這些肉眼看起來差不多的格式的其中一種。
環境
windows10
python3.7+pycharm
建立目錄
1.在程式設計前,建立一個資料夾,並放入你想用的檔案(非目錄),這些檔案的格式不合適。
例如,我在桌面建立了名為"in_path"的資料夾,在裡面放進了.pgm和.png格式的檔案,想讓他們都轉化成.jpg格式。
2.同時新建一個batch_change.py檔案。
編寫程式
匯入python的模組os,PIL,glob
// 匯入PIL,os,glob from PIL import Image import os,glob
建立輸出目錄
// 建立輸出資料夾 def batch_change(in_path,out_path): if not os.path.exists(out_path): print(out_path,'is not existed.') os.mkdir(out_path) if not os.path.exists(in_path): print(in_path,'is not existed.') return -1
瀏覽輸入目錄
// 瀏覽遍歷輸入資料夾 for files in glob.glob(in_path+'/*'): filepath,filename=os.path.split(files) out_file = filename[0:9]+'.jpg' #轉換成最終格式為.jpg,可以在這裡改為.png im = Image.open(files) new_path=os.path.join(out_path,out_file) print(count,',new_path) count = count+1 im.save(os.path.join(out_path,out_file))
修改檔案路徑
// 瀏覽遍歷輸入資料夾 if __name__=='__main__': batch_change(r'C:\Users\80610\Desktop\in_path',r'C:\Users\80610\Desktop\out_path') #你想轉化檔案所在資料夾輸入和輸出的路徑
執行結果
無論是pgm,png,他們們都轉化成.jpg格式,並且儲存在out_path資料夾下
完整程式碼
#encoding = utf-8 #author = itinerary,hui from PIL import Image import os,glob def batch_change(in_path,out_path): #引數:輸入與輸出資料夾路徑 if not os.path.exists(out_path): print(out_path,'is not existed.') #建立輸出資料夾 os.mkdir(out_path) if not os.path.exists(in_path): print(in_path,'is not existed.') return -1 count = 0 for files in glob.glob(in_path+'/*'): filepath,filename=os.path.split(files) out_file = filename[0:9]+'.png' #轉換成最終格式為png im = Image.open(files) new_path=os.path.join(out_path,out_file)) if __name__=='__main__': batch_change(r'C:\Users\80610\Desktop\in_path',r'C:\Users\80610\Desktop\out_path') #你想轉化檔案所在資料夾輸入和輸出的路近
總結
到此這篇關於python實現快速檔案格式批量轉換的方法的文章就介紹到這了,更多相關python檔案格式批量轉換內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!