python进行文件批量命名

目录

1、传递需要修改文件的上一级目录root_path,step的作用是生成不同的文件,convert_format是转化为特定的格式

2、更新

3、代码使用 

4、做数据标注的时候检查照片和其标注格式的文件名是否相同


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)

  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Q渡劫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值