文件过滤器的代码
遍历特定路径下所有文件并根据文件命名筛选文件。
import os
import os.path
import re
rootdir = "/home/GTA/GTAv3"
file_object = open('/home/moyang/Cloth-Changing-Person-REID/train_list.txt','w')#打开txt文件
#遍历所有文件路径parent为根目录,dirnames为文件夹名,filenames为文件名
for parent,dirnames,filenames in os.walk(rootdir):
for filename in filenames:
if ".jpg" in filename:#筛选所有文件名
print(filename)
pattern = re.compile(r'([\w]+)_([\w]+)_([\d]+)_([\w]+)_([\w]+)_([\d]+)_([\d]+)')
place,weather,time,action,per,pid,cid=pattern.search(filename).groups()
print (place,weather,time,action,per,pid,cid)
#各种条件
if place == 'subway' or place == 'fbi':#
if weather == 'RAIN':
if int(time)>12:
if action == 'walk':
if per == 'person':
if int(pid) <10:
print (place,weather,time,action,per,pid,cid)
file_object.write(parent+ '/' +filename+ '\n')
#写入txt文件,这里有换行符号
file_object.close()
提取txt文件中的信息
with open(file_path) as file_obj:
for img_path in file_obj:
#print(img_path.rstrip())
img_path = img_path.rstrip()#这里加rstrip是去掉后面的空格,不然读取出来会有空格
这段代码实现了一个文件过滤器,遍历指定路径下所有文件,筛选出包含'.jpg'的文件,并使用正则表达式解析文件名中的信息。然后根据特定条件(如地点、天气、时间、动作、人物等)进一步过滤,将符合条件的文件路径写入txt文件。同时,展示了从生成的txt文件中读取和处理信息的方法。

3605

被折叠的 条评论
为什么被折叠?



