python實(shí)現(xiàn)快速文件格式批量轉(zhuǎn)換的方法
用python實(shí)現(xiàn)文件夾下的成批文件格式轉(zhuǎn)換
我們對(duì)于文件轉(zhuǎn)換的需求很大,甚至于對(duì)于圖片的格式,JPG和PNG格式在肉眼看來(lái)都沒什么差別,但是對(duì)于計(jì)算機(jī)而言,它有時(shí)候就只接受這些肉眼看起來(lái)差不多的格式的其中一種。
環(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é)果
無(wú)論是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)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. python中scrapy處理項(xiàng)目數(shù)據(jù)的實(shí)例分析2. 教你在 IntelliJ IDEA 中使用 VIM插件的詳細(xì)教程3. IntelliJ IDEA導(dǎo)入jar包的方法4. js抽獎(jiǎng)轉(zhuǎn)盤實(shí)現(xiàn)方法分析5. Python requests庫(kù)參數(shù)提交的注意事項(xiàng)總結(jié)6. vue-electron中修改表格內(nèi)容并修改樣式7. iOS實(shí)現(xiàn)點(diǎn)贊動(dòng)畫特效8. 通過Python pyecharts輸出保存圖片代碼實(shí)例9. JavaScript中l(wèi)ayim之整合右鍵菜單的示例代碼10. SpringBoot參數(shù)校驗(yàn)與國(guó)際化使用教程
