亲自测试,有效
import os
import re
def reset(path):
i=0
filelist = os.listdir(path)
for files in filelist:
Olddir = os.path.join(path, files)
if os.path.isdir(Olddir):
reset(Olddir)
else:
i = i + 1
filename = os.path.splitext(files)[0]
filetype = os.path.splitext(files)[1]
filePath = path+'/'+filename+filetype
print(filePath)
alter(filePath,"large car","large_car") //第一个为原内容,第二个为修改后内容
alter(filePath,"small car","small_car")//第一个为原内容,第二个为修改后内容
def alter(file,old_str,new_str):
with open(file, "r", encoding="utf-8") as f1,open("%s.bak" % file, "w", encoding="utf-8") as f2:
for line in f1:
if old_str in line:
line = line.replace('large car', 'large_car')//第一个为原内容,第二个为修改后内容
line = line.replace('small car', 'small_car')//第一个为原内容,第二个为修改后内容
f2.write(line)
print(new_str)
os.remove(file)
os.rename("%s.bak" % file, file)
path = r"/root/autodl-tmp/yolov5_obb/dataset/dataset_demo/labelTxt/"//存放txt的路径
reset(path)
参考;
https://blog.csdn.net/Wzongming/article/details/125860240