假设需要将原索引“0,1,2,3”都修改为“0”:
import os
# 定义原始文件夹路径和新文件夹路径
path = 'labels'
new_path = 'labels_new' # 指定的新文件夹路径
# 如果新文件夹不存在,则创建它
if not os.path.exists(new_path):
os.makedirs(new_path)
# 获取原始文件夹中的所有文件
total_txt = os.listdir(path)
for filename in total_txt:
# 生成完整的文件路径
file_path = os.path.join(path, filename)
# 读取文件内容
with open(file_path, 'r') as file:
lines = file.readlines()
# 修改文件内容
for index, line in enumerate(lines):
if line[0] in ["0"]: # 简化条件检查
lines[index] = "0 " + line[2:]
# 构建新文件的路径
new_file_path = os.path.join(new_path, filename)
# 将修改后的内容写入新文件夹中的文件
with open(new_file_path, 'w') as file:
file.write("".join(lines))
print('Process completed.')