python实现快速文件格式批量转换的方法

用python实现文件夹下的成批文件格式转换
我们对于文件转换的需求很大,甚至于对于图片的格式,JPG和PNG格式在肉眼看来都没什么差别,但是对于计算机而言,它有时候就只接受这些肉眼看起来差不多的格式的其中一种。
环境
windows10
python3.7+pycharm
创建目录
1.在编程前,创建一个文件夹,并放入你想用的文件(非目录),这些文件的格式不合适。
例如,我在桌面创建了名为"in_path"的文件夹,在里面放进了.pgm和.png格式的文件,想让他们都转化成.jpg格式。
2.同时新建一个batch_change.py文件。
python实现快速文件格式批量转换的方法
文章图片

编写程序
导入python的模块os,PIL,glob.

// 导入PIL,os,globfrom PIL import Imageimport 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,可以在这里改为.pngim = Image.open(files)new_path=os.path.join(out_path,out_file)print(count,',',new_path)count = count+1im.save(os.path.join(out_path,out_file))

【python实现快速文件格式批量转换的方法】修改文件路径
// 浏览遍历输入文件夹if __name__=='__main__':batch_change(r'C:\Users\80610\Desktop\in_path',r'C:\Users\80610\Desktop\out_path') #你想转化文件所在文件夹输入和输出的路径

运行结果
无论是pgm,png,他们们都转化成.jpg格式,并且保存在out_path文件夹下
python实现快速文件格式批量转换的方法
文章图片

python实现快速文件格式批量转换的方法
文章图片

完整代码
#encoding = utf-8#author = itinerary,huifrom PIL import Imageimport os,globdef 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 -1count = 0for files in glob.glob(in_path+'/*'):filepath,filename=os.path.split(files)out_file = filename[0:9]+'.png' #转换成最终格式为pngim = Image.open(files)new_path=os.path.join(out_path,out_file)print(count,',',new_path)count = count+1im.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实现快速文件格式批量转换的方法的文章就介绍到这了,更多相关python文件格式批量转换内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

    推荐阅读