python 批量更换图片格式脚本
問題:將某文件下的所有jpg的圖片更換為png的圖片
簡單的實現:
# -*- coding:utf-8 -*- from os.path import splitext import glob from PIL import Imagedef get_all_file(filename):files = glob.glob(filename)return filesdef to_ather_file(files, type):for jpg in files:im = Image.open(jpg)png = splitext(jpg)[0]+"." + typeim.save(png)print pngif __name__ == "__main__":filename = "./image/*.[Jj][Pp][Gg]"files = get_all_file(filename)to_ather_file(files, "png")這是一種很簡單的是實現方法,就是先用glob獲得某路徑下的所有文件,該文件下都是jpg圖片(題目是給定的,也可以考慮存在其他圖片的情況的處理方式,就是獲得文件的后綴名,判斷是否為jpg),然后依次讀入圖片,使用splitext獲得文件名和后綴名,然后按照要求重組文件名并保存就好了。
這里介紹兩個部分:
glob模塊:
在python中,glob模塊是用來查找匹配的文件的 ? ?在查找的條件中,需要用到Unix shell中的匹配規則: ? ??
? * ? ?: ? 匹配所所有 ? ? ??
? ? ? ?: ? 匹配一個字符 ? ? ??
*.* ?: ? 匹配如:[hello.txt,cat.xls,xxx234s.doc] ? ??
? ?.* ?: ? 匹配如:[1.txt,h.py] ? ??
? ?.gif: ? 匹配如:[x.gif,2.gif] ??
?可以參考:fnmatch ? ?如果沒有匹配的,glob.glob(path)將返回一個空的list:[]
也就說:glob是用來尋找文件的。某種命名規則的文件的。
import globdef get_all():'''獲取目錄[c:\\tmp]下面所有的文件'''return glob.glob('c:\\tmp\\*.*')def get_my_file():'''獲取目錄[c:\\tmp]下面文件名為4個字符的文件'''return glob.glob('c:\\tmp\\????.txt')def get_batch_file():'''獲取目錄[c:\\tmp]下面擴展名為\'.txt\'的文件'''return glob.glob('c:\\tmp\\*.txt')def main():print('獲取目錄[c:\\tmp]下面所有的文件:')tem_files = get_all()print(tem_files)print('獲取目錄[c:\\tmp]下面文件名為4個字符的文件:')tem_files = get_my_file()print(tem_files)print('獲取目錄[c:\\tmp]下面擴展名為\'.txt\'的文件:')tem_files = get_batch_file()print(tem_files)if __name__ == '__main__':main()
python文件操作:?
有關文件夾與文件的查找,刪除等功能 在?os?模塊中實現。使用時需先導入這個模塊,
導入的方法是:
import os
1、將一個路徑名分解為目錄名和文件名兩部分
fpath , fname = os.path.split( "你要分解的路徑")
例如:
a, b =?os.path.split( "c:\\123\\456\\test.txt" )
print a
print b
顯示:
c:\123\456
test.txt
?
2、 分解文件名的擴展名
fpathandname , fext = os.path.splitext( "你要分解的路徑")
例如:
a, b =?os.path.splitext( "c:\\123\\456\\test.txt" )
print a
print b
顯示:
c:\123\456\test
.txt
文件操作還有很多有用的函數,可以通過查找手冊來看。
轉載于:https://www.cnblogs.com/silence-hust/p/4266182.html
總結
以上是生活随笔為你收集整理的python 批量更换图片格式脚本的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: POJ 3241 Object Clus
- 下一篇: 用VS连接oracle数据库时ORA-1