import os
import re
# 定义要修改的数字和替换数字
original_number = '0'
new_number = '1' # 将 '1' 替换为您想要替换成的数字
# 定义文件夹路径
folder_path = r'F:\yolov5\yolov5-5.0\Recyclable-plastic\valid\labels'
# 遍历文件夹中的所有文件
for filename in os.listdir(folder_path):
if filename.endswith('.txt'): # 确保只处理 .txt 文件
match = re.search(r'\d+', filename)
if match:
match = int(match.group())
if match > int(419) and match < int(481):
file_path = os.path.join(folder_path, filename)
with open(file_path, 'r') as file:
lines = file.readlines()
modified_lines = []
for line in lines:
parts = line.split()
parts[0] = new_number # 替换第一列的数字
modified_lines.append(' '.join(parts))
for i in modified_lines:
print(i)
print(str(match) + "next")
with open(file_path, 'w') as file:
for i in modified_lines:
file.write(i+'\n')
批量更改yolov5数据集的第一列数字
最新推荐文章于 2024-05-29 17:20:59 发布
本文介绍了如何使用Python脚本,针对Yolov5项目的特定文件夹中.txt文件,查找并替换特定范围内的数字。脚本通过正则表达式搜索文件名中的数字,然后读取文件内容,替换第一列的数字,并将修改后的行写回原文件。
摘要由CSDN通过智能技术生成