Python Nested Loop Doesn't Loop
I'm a python beginner and I can't make my loop loop. Here's the case : I've got two csv files (event logs). First on is called bd8result.csv with 4 or 5 lines structured like these
Solution 1:
After one iteration of looping over reader2
, reader1
is exhausted by its for loop and raises StopIteration
and won't return anything in the successive loops.
You should get a new instance of csv.reader
in every iteration:
withopen('result_'+ namefile +'.csv', 'rb') as master1:
forrowin csv.reader(master1):
target =row[1]
lecteur =row[5]
epoch_ref =int(row[-1])
withopen('epoch_'+ namefile +'.csv', 'rb') as hosts1:
for row2 in csv.reader(hosts1):
epoch1 =int(row2[-1])
lecteur1 = row2[5]
withopen('result_scout'+ namefile +'.csv', 'a') as results1:
if epoch1 > (epoch_ref - ecart) and epoch1 < (epoch_ref + ecart) and lecteur1 == lecteur:
writer1 = csv.writer(results1)
writer1.writerow([target]+[sys.argv[1]]+row2)
results1.close()
From the documentation:
csv.reader(csvfile)
Return a reader object which will iterate over lines in the given csvfile. csvfile can be any object which supports the iterator protocol and returns a string each time its next() method is called.
This implies that after the reader raises StopIteration
it will be exhausted just like an exhausted generator.
Post a Comment for "Python Nested Loop Doesn't Loop"