Python 嵌套循环不循环

Python nested loop doesn't loop

我是 python 初学者,我不会循环。

情况如下:我有两个 csv 文件(事件日志)。

首先是 bd8result.csv,有 4 或 5 行,结构如下:

2015/10/30 09:53:44,blabla1,259373865,95,F,A1 IP Thers,A1SIP V1 (R),-,,1446195224
2015/10/30 11:03:14,blabla2,259431070,32,F,A7 IP MornOs,A7SIP V1 (R),-,,1446199394
2015/10/30 21:30:59,blabla3,259980991,86,F,A2 IP Hor4ain,A2IP V1 (R),-,,1446237059

第一列是日期,第二列是 IP 事件(目标),最后一列是纪元时间。

我需要在具有相同结构的更大日志文件中找到 blabla1、blabla2 和 blabla3 以及这些事件发生前 20 分钟和发生后 20 分钟的相关事件,并将结果写入 csv 文件。 我只是收集位于相同 lecteur 信息上的事件(if... 中的测试也是如此)。

我的代码如下所示:

with open('result_'+ namefile + '.csv', 'rb') as master1, open('epoch_'+ namefile + '.csv', 'rb') as hosts1:
    reader2 = csv.reader(master1)
    reader1 = csv.reader(hosts1)
    for row in reader2:
        target = row[1]
        lecteur = row[5]
        epoch_ref = int(row[-1])
        for row2 in reader1:
            epoch1 = int(row2[-1])
            lecteur1 = row2[5]
            with open('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()

我的问题是它正确执行了第一项 (blabla1[​​=35=]),但没有为 blabla2 和 blabla3 写入任何内容。

我尝试了几种方法,但还是卡住了。

感谢任何帮助。谢谢!

reader2 的一次循环之后,reader1 被其 for 循环耗尽并引发 StopIteration 而不会 return 在后续循环中发生任何事情。

你应该在每次迭代中得到一个新的 csv.reader 实例:

with open('result_'+ namefile + '.csv', 'rb') as master1:
    for row in csv.reader(master1):
        target = row[1]
        lecteur = row[5]
        epoch_ref = int(row[-1])
        with open('epoch_'+ namefile + '.csv', 'rb') as hosts1:
            for row2 in csv.reader(hosts1):
                epoch1 = int(row2[-1])
                lecteur1 = row2[5]
                with open('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()

来自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.

这意味着在 reader 加注后 StopIteration 它将像耗尽的发电机一样耗尽。