数据集 图片 批量重命名 python实现

将一个文件夹下所有图片重命名为编号递增的形式,并以0补全所需要的位数

原始图片文件名:

数据集 图片 批量重命名 python实现_第1张图片

重命名后的文件名:

数据集 图片 批量重命名 python实现_第2张图片

下面是python代码的实现:

import os
path = "F:/project/PycharmProjects/renamePY/infraredsmall/cloud/img"
filelist = os.listdir(path) #该文件夹下所有的文件(包括文件夹)
count=1#设置图片编号从1开始
for file in filelist:#打印出所有图片原始的文件名
    print(file)
for file in filelist:   #遍历所有文件
    Olddir=os.path.join(path,file)   #原来的文件路径
    if os.path.isdir(Olddir):   #如果是文件夹则跳过
        continue
    filename=os.path.splitext(file)[0]   #文件名
    filetype=os.path.splitext(file)[1]   #文件扩展名
    Newdir=os.path.join(path,str(count).zfill(6)+filetype)  #用字符串函数zfill 以0补全所需位数
    os.rename(Olddir,Newdir)#重命名
    count+=1

 这里设置图片编号从1开始,也可以自主设置开始的位置。

 

你可能感兴趣的:(python)