做数据集的时候经常需要把文件捣鼓来捣鼓去,还是决定留个批量重命名的小demo
代码如下:
import os
def rename_batch(txt_path, img_path):
"""
此方法会对输入目录下的文件进行重命名批处理
如果日后需要源数据,使用前最好先对源数据进行备份,
:param txt_path: 输入txt文件的上级目录
:param img_path: 输入图片的上级目录
:return: None
"""
# 获取绝对路径下文件列表 这里以txt和jpg格式文件为例
txt_name = os.listdir(txt_path)
img_name = os.listdir(img_path)
tag = 1
# 遍历每个txt
for txt in txt_name:
t = txt.split('.', -1) # 将txt文件名 例如 'temp.txt' 分段存储 t=['temp','txt']
name_new = 'fire_val_' + str(tag) # 要改成什么名字,不包括后缀
# 在图片中找到同名文件
for img in img_name:
if img.split('.', -1)[0] == t[0]:
old_img_name = img_path + os.sep + img # os.sep为系统分隔符
new_img_name = img_path + os.sep + name_new + '.jpg'
os.rename(old_img_name, new_img_name)
print(str(img)+'------->'+str(name_new)+'.jpg')
old_txt_name = txt_path + os.sep + txt
new_txt_name = txt_path + os.sep + name_new + '.txt'
os.rename(old_txt_name, new_txt_name)
print(str(txt)+'------->'+str(name_new)+'.txt')
print()
tag += 1
if __name__ == '__main__':
txt_pth = r"E:\python_workdir\dataset\coco\labels\val2017"
img_path = r"E:\python_workdir\dataset\coco\images\val2017"
rename_batch(txt_pth, img_path)