文件过滤器的代码
遍历特定路径下所有文件并根据文件命名筛选文件。
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是去掉后面的空格,不然读取出来会有空格