问题描述
文件夹下的图片后缀不统一,有.jpg、.JPG、.tiff等,现在需要统一改为.jpg
解决方法
import os
#想要更改图片所在的根目录
rootdir=r"D:\Temp"
#获取目录下文件名清单
files=os.listdir(rootdir)
#对文件名清单里的每一个文件名进行处理
for filename in files:
portion=os.path.splitext(filename) #portion为名称和后缀分离后的列表 #os.path.splitext()将文件名和扩展名分开
if portion[1]!=".jpg": #如果不为jpg则更改名字 # 也可以用==,改需要改的名字
newname=portion[0]+".jpg" #要改的新后缀 #改好的新名字
print(filename) #打印出要更改的文件名
os.chdir(rootdir) #修改工作路径
os.rename(filename,newname) #在工作路径下对文件名重新命名
附加知识
import os
import shutil
os.getcwd() # 获取当前工作目录,非脚本目录
os.listdir() # 返回指定目录下的所有文件和目录,非递归
os.remove() # 删除文件
os.removedirs() #删除目录
os.path.isfile() # 检验给出的路径是否是一个文件
os.path.isdir() # 检验给出的路径是否是一个目录
os.path.isabs() # 判断是否是绝对路径
os.path.exists() # 检验给出的路径是否真实存在
os.path.split() # 返回一个路径的目录名和文件名
os.path.splitext() # 分离文件扩展名
os.path.dirname() # 获取文件路径名
os.path.basename() # 获取一个绝对路径下的文件名
os.system() # 运行shell命令
os.rename(old,new) # 重命名文件或目录
os.makedirs(r"c:\python\test") # 创建多级目录
os.mkdir("test") # 创建单个目录
os.exit() # 终止当前进程
os.path.getsize(filename) # 获取文件大小
os.mknod("test.txt") # 创建空文件
shutil.copyfile("oldfile","newfile") # oldfile和newfile都只能是文件
shutil.copytree("olddir","newdir") # olddir和newdir都只能是目录,且newdir必须不存在
shutil.move("oldpos","newpos") # 移动文件或目录
shutil.rmtree("dir") # 删除目录,与os.removedirs()相同
os.path.join(“home”, "me", "mywork") # 路径连接
参考
https://blog.csdn.net/weixin_39450145/article/details/105093699
https://blog.csdn.net/T1243_3/article/details/80170006
https://blog.csdn.net/xiewenrui1996/article/details/109353327