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

这篇文章主要介绍了python实现快速文件格式批量转换的方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

用python实现文件夹下的成批文件格式转换

我们对于文件转换的需求很大,甚至于对于图片的格式,JPG和PNG格式在肉眼看来都没什么差别,但是对于计算机而言,它有时候就只接受这些肉眼看起来差不多的格式的其中一种。

环境

windows10
python3.7+pycharm

创建目录

1.在编程前,创建一个文件夹,并放入你想用的文件(非目录),这些文件的格式不合适。
例如,我在桌面创建了名为"in_path"的文件夹,在里面放进了.pgm和.png-600格式的文件,想让他们都转化成.jpg-600格式。
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-600' #转换成最终格式为.jpg-600,可以在这里改为.png-600 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-600格式,并且保存在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-600' #转换成最终格式为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实现快速文件格式批量转换的方法的文章就介绍到这了,更多相关python文件格式批量转换内容请搜索html中文网以前的文章或继续浏览下面的相关文章希望大家以后多多支持html中文网!

以上就是python实现快速文件格式批量转换的方法的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » python