Python筛选特定文件夹下特定命名格式的文件并保存和读取txt文件

文件过滤器的代码

遍历特定路径下所有文件并根据文件命名筛选文件。

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是去掉后面的空格,不然读取出来会有空格
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

KingsMan666

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值