网络编程
位置:首页>> 网络编程>> Python编程>> python实现快速文件格式批量转换的方法

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

作者:itinerary,hui  发布时间:2021-10-31 22:53:12 

标签: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,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文件夹下

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

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

完整代码


#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') #你想转化文件所在文件夹输入和输出的路近

总结

来源:https://blog.csdn.net/weixin_50683750/article/details/109110483

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com