python如何實現快速文件格式批量轉換?針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
用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)
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') #你想轉化文件所在文件夾輸入和輸出的路近關于python如何實現快速文件格式批量轉換問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業資訊頻道了解更多相關知識。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。