Python文件读取并写入txt文件的简单实现
import os import numpy as np # # name:txt文件名 # rootdir:根路径 # metaimage:原始图像路径 # imglabel:标签图像路径 # def write_to_txt(name, root_dir, metaimage, imglabel): txt_path = root_dir + name + \'.txt\' txt = open(txt_path, \'w\') for (i,j) in zip(metaimage,imglabel): image_dir = os.path.join(str(i)) # image_dir = os.path.join(\'./data/metaimage/\', str(i)) label_dir = os.path.join(str(j)) # label_dir = os.path.join(\'./data/imglabel/\', str(j)) # 截取文件名 txt.write(image_dir[0:-4] + \'\n\') txt.write(label_dir[0:-4] + \'\n\') def read_image(path1, path2): filelist1 = os.listdir(path1) meta_image = np.array([file for file in filelist1 if file.endswith(\'.jpg\')], dtype=object) print("-------len(metaimage):", len(meta_image)) filelist2 = os.listdir(path2) img_label = np.array([file for file in filelist2 if file.endswith(\'.png\')], dtype=object) print("-------len(imglabel):", len(img_label)) return meta_image, img_label path1 = r\'data/VOCtrainval_11-May-2012/VOCdevkit/Meta/JPEGImages\' path2 = r\'data/VOCtrainval_11-May-2012/VOCdevkit/Meta/SegmentationClass\' metaimage, imglabel = read_image(path1, path2) write_to_txt(\'train\', \'./data/\', metaimage, imglabel)
版权声明:本文为dyc99原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。