如何在python中从多个文件中搜索具有条件的多个信息



我试图在目录和所有子文件夹中的所有.output文件中搜索'TestTime'和'Runtime ',如果我在该文件中找到'TestTime',我只需要Runtime,下面是我的代码:

import os
import os.path
import csv
path = '/user/data/2022/test'
foutput = [f for f in os.listdir(path) if f.endswith('.OUTPUT')]
fout = open('Res', 'w')
fieldnames =['Design', 'Run time', 'Test Time']
writer = csv.DictWriter(fout, fieldnames=fieldnames)
writer.writeheader()
for root,dirs,files in os.walk(path):
for file in [f for f in files if f.endswith(".OUTPUT")]:            
with open(os.path.join(root,file), 'r') as fin:
lines = fin.readline()
for line in lines:
flag = 0 
if(line.find('Test time')):
flag =1 #  set a flag when I got TestTime 
TestTime = line.split()# save my test time data, and ask keep reading from current file to search 'Run time'                          
continue
if(line.find('phys_opt_design: Time (s):') and flag == 1):                                
RunTime = line.split(":")
writer.writerow({'Design': fin.name, 'Test time': TestTime[5], 'Run time':RunTime[0] }) 


fin.close()
fout.close()

但是它不像预期的那样工作,只从一个文件中准备好了,有人能帮助吗?

要使此代码工作,请使用re模块,您可以在其中编写正则表达式来匹配您正在查找的信息。

#sample
import re
pattern = re.compile(line)
match = pattern.find('Test time')

应该可以

最新更新