import os# 需要查找的行
lines_to_find = ["1 0.428500 0.266667 0.100000 0.196000","1 0.227625 0.284667 0.081250 0.092667","1 0.251125 0.791000 0.106250 0.151333"
]# 文件夹路径
folder_path = r'E:\data_seg\data_detect\216_813'# 遍历文件夹中的所有文件
for filename in os.listdir(folder_path):if filename.endswith('.txt'):file_path = os.path.join(folder_path, filename)with open(file_path, 'r') as file:lines = file.readlines()# 查找与给定行匹配的行,并修改for i, line in enumerate(lines):if line.strip() in lines_to_find:lines[i] = '3' + line[1:]# 将修改后的内容写回文件with open(file_path, 'w') as file:file.writelines(lines)
上面的代码实现批量修改把 下面几个的 把1 改成3
"1 0.428500 0.266667 0.100000 0.196000",
"1 0.227625 0.284667 0.081250 0.092667",
"1 0.251125 0.791000 0.106250 0.151333"