本文主要是介绍python 对TXT文档的操作记录,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一、读取txt的每一行且修改行中指定的内容
import os
import cv2def get_files(path):""" 获取指定路径下所有文件名称 """files = []for filename in os.listdir(path):if os.path.isfile(os.path.join(path, filename)):files.append(filename)return filesdef split_to_name_ext(image_name_ext):name, ext = os.path.splitext(image_name_ext)return name, extdef gen_empty_txt(txt_path):with open(txt_path, "w") as f:passlabels_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']:continuelabel_path=labels_txt_path+labelprint(label_path)save_path_new=save_path+labelprint(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]=2if(words[0]=="2"):# print(words[0])words[0]=0print(words)print(type(words))hh=" "nnn=map(str,words)result =hh.join(nnn)# print(result)file_write.writelines(result)file_write.writelines("\n")
这篇关于python 对TXT文档的操作记录的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!