I know that my friends have encountered batch renaming of photos, but I don’t know how to do it. Today I will share with you how to use python to batch rename photos. Here I will change the photos of the glory of the king that I climbed down. Numbers in sequence to name, the code is as follows, and the idea is also in the code:
import os,time
#首先我们需要导入oshetime这两个模块,这里time模块其实可以不用导入的
#跟我们功能的实现没有什么太大的关系,只是为了统计处理了多长时间
#os模块提供通用的、基本的和操作系统交互功能
#time模块是python处理时间的模块
#str.split(string)分割字符串 .join(list)组成字符串
#我们先直接定义一个处理照片的函数,然后在函数里面去实现它的功能
def change_name(path):
global i #这里我们先声明一个全局变量i
#然后我们先用if语句判断传输进来的路径是不是文件夹或者文件
#如果不是就直接返回False
if not os.path.isdir(path) and not os.path.isfile(path):
return False
#再用if语句判断是不是文件,如果是文件,那么我们的操作就可以开始了
if os.path.isfile(path):
#这里我们用os.path.split()分割出目录和文件
#索引为1的是文件,索引为0的是目录
file_path = os.path.split(path)
#这里再用split()函数分割出文件名和后缀名
lists = file_path[1].split('.')
#然后使用列表切片操作截取出后缀名
file_ext = lists[-1]
#这里定义一个图片后缀名的列表,后面判断使用
#这里其实不用定义这么多,其实有jpg,jpeg,png就够了
img_ext = ['bmp','jpeg','gif','psd','png','jpg']
#用if语句判断截取出来的后缀名是否在我们定义的列表中
if file_ext in img_ext:
#如果在的话就该进行改名操作了
#这里用到我们的os.rename方法修改文件的名字
os.rename(path,file_path[0] + '/' + str(i) + '.' + file_ext)
#改名完成让全局变量加1
i += 1
#如果这个是文件夹
elif os.path.isdir(path):
#那么就用os.listdir获取文件夹包含的文件或文件夹的名字的列表
# 然后遍历
for x in os.listdir(path):
#最后用os.path.join拼接路径,然后递归使用函数就好了
change_name(os.path.join(path,x))
#函数已经写好了,现在就是来使用了
#我们先定义自己图片所在的路径
img_dir = 'G:\Python\pig'
#在函数执行前,获取一个时间戳
start = time.time()
#给全局变量i赋值
i = 0
#执行函数
change_name(img_dir)
#函数执行结束后获取一个时间戳,然后减去之前的时间戳
#就是我们处理照片的时间了
c = time.time() - start
print("程序运行耗时:",c)
print("共处理",i,"张照片")
This is the result of our execution. We processed more than 80 photos and didn't use it for a minute:
The following picture is the original name of some pictures:
This is the modified name
Have you learned it? If you learn it, hurry up and try it! ! !