一、读取txt的每一行且修改行中指定的内容
import os
import cv2
def get_files(path):
""" 获取指定路径下所有文件名称 """
files = []
for filename in os.listdir(path):
if os.path.isfile(os.path.join(path, filename)):
files.append(filename)
return files
def split_to_name_ext(image_name_ext):
name, ext = os.path.splitext(image_name_ext)
return name, ext
def gen_empty_txt(txt_path):
with open(txt_path, "w") as f:
pass
labels_txt_path='F:/yolov5_train1_8/labels2/'
save_path='F:/yolov5_train1_8/lable_fix/'
txt_path='F:/yolov5_train1_8/lable/Image_20240628141820123.txt'
labels_file = get_files(labels_txt_path)
for label in labels_file:
name, ext = split_to_name_ext(label)
print(label)
if ext not in ['.txt']:
continue
label_path=labels_txt_path+label
print(label_path)
save_path_new=save_path+label
print(save_path_new)
file_write = open(save_path_new, "w")
# with open(label_path, 'r') as file:
# first_line = file.readline()
# print(first_line)
with open(label_path, 'r') as file:
for line in file:
print(line.strip())
words = line.split()
print(words)
if(len(words)>1):
# if(words[0]=="1"):
# # print(words[0])
# words[0]=2
if(words[0]=="2"):
# print(words[0])
words[0]=0
print(words)
print(type(words))
hh=" "
nnn=map(str,words)
result =hh.join(nnn)
# print(result)
file_write.writelines(result)
file_write.writelines("\n")