Reputation: 31
i read a file and group it by a keyword. I have also a List, how can i check it if a value from list is in group? Not check only one entry, check all entries in list against group.
Example but not checked list against group. I dont wanna write if any or any blabla.
hosts = ['blabla.dyndns.org','blabla1.dyndns.org']
with open(testfile,'r') as f:
for key,group in it.groupby(f,lambda line: line.startswith('[hosts]')):
if not key:
group = list(group)
if any("blabla.dyndns.org" in s for s in group) or any("blabla.dyndns.org" in s for s in group):
print 'yes'
else:
print 'no'
Thank you, regards.
I wanna script that i can in example change protocol of some hosts.
import itertools as it
testfile='blabla.txt'
hosts = set(['blabla.dyndns.org','blabla1.dyndns.org'])
with open(testfile,'r') as f:
for key,group in it.groupby(f,lambda line: line.startswith('[host]')):
if not key:
group = set(group)
if group & hosts: # set intersection
print '[host]\n'
for (i, item) in enumerate(group):
if 'protocol' in item:
group[i] = 'protocol = udp\n'
j = ', '.join(group)
y = j.replace(", ", "")
print y
else:
print '[host]\n'
j = ', '.join(group)
y = j.replace(", ", "")
print y
exit(0)
Does not work.
Upvotes: 1
Views: 255
Reputation: 179452
Use set intersection:
hosts = set(['blabla.dyndns.org','blabla1.dyndns.org'])
with open(testfile,'r') as f:
for key,group in it.groupby(f,lambda line: line.startswith('[hosts]')):
if not key:
group = set(group)
if group & hosts: # set intersection
print 'yes'
else:
print 'no'
Upvotes: 2