Reputation: 5488
I have a script that searches through config files and finds all matches of strings from another list as follows:
dstn_dir = "C:/xxxxxx/foobar"
dst_list =[]
files = [fn for fn in os.listdir(dstn_dir)if fn.endswith('txt')]
dst_list = []
for file in files:
parse = CiscoConfParse(dstn_dir+'/'+file)
for sfarm in search_str:
int_objs = parse.find_all_children(sfarm)
if len(int_objs) > 0:
dst_list.append(["\n","#" *40,file + " " + sfarm,"#" *40])
dst_list.append(int_objs)
I need to change this part of the code:
for sfarm in search_str:
int_objs = parse.find_all_children(sfarm)
search_str
is a list containing strings similar to ['xrout:55','old:23']
and many others.
So it will only find entries that end with the string from the list I am iterating through in sfarm
. My understanding is that this would require my to use re
and match on something like sfarm$
but Im not sure on how to do this as part of the loop.
Am I correct in saying that sfarm
is an iterable? If so I need to know how to regex on an iterable object in this context.
Upvotes: 2
Views: 263
Reputation: 4196
Please check this code. Used glob module to get all "*.txt" files in folder.
Please check here for more info on glob module.
import glob
import re
dst_list = []
search_str = ['xrout:55','old:23']
for file_name in glob.glob(r'C:/Users/dinesh_pundkar\Desktop/*.txt'):
with open(file_name,'r') as f:
text = f.read()
for sfarm in search_str:
regex = re.compile('%s$'%sfarm)
int_objs = regex.findall(text)
if len(int_objs) > 0:
dst_list.append(["\n","#" *40,file_name + " " + sfarm,"#" *40])
dst_list.append(int_objs)
print dst_list
Output:
C:\Users\dinesh_pundkar\Desktop>python a.py
[['\n', '########################################', 'C:/Users/dinesh_pundkar\\De
sktop\\out.txt old:23', '########################################'], ['old:23']]
C:\Users\dinesh_pundkar\Desktop>
Upvotes: 1
Reputation: 52929
Strings in python are iterable, so sfarm
is an iterable, but that has little meaning in this case. From reading what CiscoConfParse.find_all_children()
does, it is apparent that your sfarm
is the linespec
, which is a regular expression string. You do not need to explicitly use the re
module here; just pass sfarm
concatenated with '$'
:
search_string = ['xrout:55','old:23']
...
for sfarm in search_str:
int_objs = parse.find_all_children(sfarm + '$') # one of many ways to concat
...
Upvotes: 2