方法一: 适用win和linux
import osimport sysfrom PIL import Imageinput_folder=r'F:\VOC\PNGImages' #源文件夹,包含.png格式图片output_folder=r'F:\VOC\jpg_image'# 输出文件夹#training_data=[] a=[]for root, dirs, files in os.walk(input_folder):for filename in (x for x in files if x.endswith('.png')):filepath = os.path.join(root, filename) object_class = filename.split('.')[0]a.append(object_class)print(a)for i in a:old_path=input_folder+"\\"+str(i)+'.png'new_path=output_folder+"\\"+str(i)+'.jpg'img=Image.open(old_path)img.save(new_path)
方法二: 只适合win,这种编码linux不识别
import osimport stringdirName = "D:your path\\" #最后要加双斜杠,不然会报错li=os.listdir(dirName)for filename in li:newname = filenamenewname = newname.split(".")if newname[-1]=="png":newname[-1]="jpg"newname = str.join(".",newname) #这里要用str.joinfilename = dirName+filenamenewname = dirName+newnameos.rename(filename,newname)print(newname,"updated successfully")