我们有时候需要将某文件夹下的所有子文件(.txt、.jpg…)进行遍历并按名称排序,然后对其内容进行读取,最后对读取的内容处理并保存。
下面使用python来实现。
代码如下:
说明:本代码可能没有删去多余的包和语句,但不影响该功能的实现。
import sys
import os
import glob
import xml.etree.ElementTree as ET
path = "F:\\lystudy\\yolostudy\\secondyolo-01\\input\\ground-truth"
filelist = os.listdir(path) #遍历该文件夹下所有的文件(包括文件夹)
filelist.sort(key=lambda x:int(x[:-4])) #按文件名倒着数第四位开始排序,默认从小到大
for image_id in filelist:
print(image_id)
position=path+"\\"+image_id
aa=image_id.strip('.txt')
print(aa)
with open(position,"r")as f1, open("F:\\lystudy\\yolostudy\\secondyolo-01\\input\\ground-truth1\\name.txt","a")as f2:
for line in f1:
f2.write("%s \n" %(line))
print("整理完成")
结果如下:
图1 原始txt文件
图2 原始txt文件
图3 最终txt文件
其中,图1是原来的txt文件1.txt数据,图2是原来的txt文件2.txt数据,图3是数据整理保存后的txt文件