Yolo格式数据集标签文件的序号更改
import os
def replace_first_digit(file_path):
# 打开文件
with open(file_path, 'r') as f:
lines = f.readlines()
# 如果文件不为空,且第一行不为空,且第一行的第一个字符是数字
if len(lines) > 0 and lines[0].strip() and lines[0][0].isdigit():
# 进行替换
if lines[0][0] == str(4):
lines[0] = lines[0].replace('4', '3')
print(f'{i}: {lines[0]}')
else:
if lines[0][0] == str(3):
lines[0] = lines[0].replace('3', '1')
print(f'{i}: {lines[0]}')
# 保存修改后的文件
with open(file_path, 'w') as f:
f.writelines(lines)
# 指定目录路径
dir_path = r'Yours labels path'
# 遍历目录下的所有txt文件
for file_name in os.listdir(dir_path):
if file_name.endswith('.txt'):
file_path = os.path.join(dir_path, file_name)
replace_first_digit(file_path)
print(f'Finished')