python實(shí)現(xiàn)快速文件格式批量轉(zhuǎn)換的方法
用python實(shí)現(xiàn)文件夾下的成批文件格式轉(zhuǎn)換
我們對于文件轉(zhuǎn)換的需求很大,甚至于對于圖片的格式,JPG和PNG格式在肉眼看來都沒什么差別,但是對于計(jì)算機(jī)而言,它有時(shí)候就只接受這些肉眼看起來差不多的格式的其中一種。
環(huán)境
windows10python3.7+pycharm
創(chuàng)建目錄
1.在編程前,創(chuàng)建一個(gè)文件夾,并放入你想用的文件(非目錄),這些文件的格式不合適。例如,我在桌面創(chuàng)建了名為'in_path'的文件夾,在里面放進(jìn)了.pgm和.png格式的文件,想讓他們都轉(zhuǎn)化成.jpg格式。2.同時(shí)新建一個(gè)batch_change.py文件。
編寫程序
導(dǎo)入python的模塊os,PIL,glob.
// 導(dǎo)入PIL,os,globfrom PIL import Imageimport os,glob
創(chuàng)建輸出目錄
// 創(chuàng)建輸出文件夾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’ #轉(zhuǎn)換成最終格式為.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:Users80610Desktopin_path’,r’C:Users80610Desktopout_path’) #你想轉(zhuǎn)化文件所在文件夾輸入和輸出的路徑
運(yùn)行結(jié)果
無論是pgm,png,他們們都轉(zhuǎn)化成.jpg格式,并且保存在out_path文件夾下
完整代碼
#encoding = utf-8#author = itinerary,huifrom PIL import Imageimport os,globdef batch_change(in_path,out_path): #參數(shù):輸入與輸出文件夾路徑 if not os.path.exists(out_path): print(out_path,’is not existed.’) #創(chuàng)建輸出文件夾 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’ #轉(zhuǎn)換成最終格式為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:Users80610Desktopin_path’,r’C:Users80610Desktopout_path’) #你想轉(zhuǎn)化文件所在文件夾輸入和輸出的路近
總結(jié)
到此這篇關(guān)于python實(shí)現(xiàn)快速文件格式批量轉(zhuǎn)換的方法的文章就介紹到這了,更多相關(guān)python文件格式批量轉(zhuǎn)換內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. JAMon(Java Application Monitor)備忘記2. 如何清空python的變量3. Python 如何展開嵌套的序列4. 在JSP中使用formatNumber控制要顯示的小數(shù)位數(shù)方法5. Spring security 自定義過濾器實(shí)現(xiàn)Json參數(shù)傳遞并兼容表單參數(shù)(實(shí)例代碼)6. Java類加載機(jī)制實(shí)現(xiàn)步驟解析7. Python TestSuite生成測試報(bào)告過程解析8. Python os庫常用操作代碼匯總9. Python OpenCV去除字母后面的雜線操作10. 增大python字體的方法步驟
