目录
1、传递需要修改文件的上一级目录root_path,step的作用是生成不同的文件,convert_format是转化为特定的格式
1、传递需要修改文件的上一级目录root_path,step的作用是生成不同的文件,convert_format是转化为特定的格式
import os
def convert(root_path, step, convert_format):
"""
root_paht: 根目录路径
step:步长开始
convert_format:转换文件格式
"""
images_name_list = os.listdir(root_path)
for image_name in images_name_list:
src_image_path = os.path.join(root_path, image_name)
print("原文件名称",src_image_path)
dst_image_path = os.path.join(root_path, "{}".format(step)+"{}".format(convert_format))
print("修改名称",dst_image_path)
os.rename(src_image_path, dst_image_path)
step += 1
2、更新
由于上面的代码中使用os.listdir得到的是一个乱序的文件名称列表,所以对于上面的代码进行调整,使得在批处理命名时可以根据文件名称大小顺序进行重命名,保证命名的正确性(注意:我的文件名称都是由数字.txt/数字.jpg格式的)
def convert(root_path, step, convert_format):
"""
root_paht: 根目录路径
step:步长开始
convert_format:转换文件格式
"""
images_name_list = os.listdir(root_path)
images_name_list.sort(key=lambda x:int(x.split('.')[0])) # 对"."进行切片操作,并取列表的第一个值(左边文件名)转化为整数
for image_name in images_name_list:
src_image_path = os.path.join(root_path, image_name)
dst_image_path = os.path.join(root_path, "{}".format(step)+"{}".format(convert_format))
os.rename(src_image_path, dst_image_path)
step += 1
print(step)
3、代码使用
root_path = "F:\\image\\image_data\\1\\163_293"
step = 163
convert_format = '.jpg'
convert(root_path=root_path,step=step, convert_format=convert_format)
4、做数据标注的时候检查照片和其标注格式的文件名是否相同
labels_root = "F:\image\image_data\\5\\21_12_09_ 060127 - 副本"
images_root = "F:\image\image_data_tag\\5\\21_12_09_ 060127 - 副本"
labels_list = os.listdir(labels_root)
labels_list.sort(key=lambda x:int(x.split('.')[0]))
images_list = os.listdir(images_root)
images_list.sort(key=lambda x:int(x.split('.')[0]))
for label_name,image_name in zip(labels_list, images_list):
print(label_name, image_name)