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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

itinerary,hui   2020-10-16 我要评论

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

总结

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们