简体   繁体   English

python csv文件和for循环

[英]python csv files and for loops

First time caller here ... 这里第一次来电...

For some reason, I am not getting the desired result from my "for" loops. 出于某种原因,我没有从“for”循环中获得所需的结果。 Below is the snippet of code. 下面是代码片段。 The loops work perfectly first time through as LOOP 2 does in fact return back to LOOP 1. But second time through LOOP 2 does not execute. 循环第一次完美地工作,因为LOOP 2实际上返回到LOOP 1.但第二次通过LOOP 2不执行。 I haven't written code in 25 years, but loving Python. 我有25年没有编写代码,但是爱Python。 Just need to get through some initial trial and error. 只需要通过一些初步的试验和错误。 Thanks in advance to anyone who can advise on this topic. 提前感谢任何可以就此主题提供建议的人。

import csv

filename='cookie_data.csv'
lookup_filename='ip_addresses.csv'

with open(filename) as file_object, open(lookup_filename) as lookup_file_object:

    reader=csv.DictReader(file_object)
    l_reader=csv.DictReader(lookup_file_object)

    for row in reader:
        user_ip=row['ip_address']
        print("LOOP 1 " + user_ip)

        for l_row in l_reader:
            lookup_ip=l_row['lookup_ip']
            print("LOOP 2 " + user_ip + lookup_ip)

The output looks like this: LOOP 1 99.246.228.140 LOOP 2 99.246.228.140 LOOP 2 137.104.238.184 LOOP 2 137.104.238.184 LOOP 2 99.246.228.140 LOOP 2 81.182.15.119 LOOP 1 137.104.238.184 LOOP 1 137.104.238.184 LOOP 1 74.110.238.103 输出如下:LOOP 1 99.246.228.140 LOOP 2 99.246.228.140 LOOP 2 137.104.238.184 LOOP 2 137.104.238.184 LOOP 2 99.246.228.140 LOOP 2 81.182.15.119 LOOP 1 137.104.238.184 LOOP 1 137.104.238.184 LOOP 1 74.110。 238.103

I intend to test for a match of the string(ip address) each time through the loop. 我打算每次通过循环测试字符串(ip地址)的匹配。 The first loop is fine, then second time through it does not execute loop 2. 第一个循环很好,然后第二次循环不执行循环2。

The problem is that your readers are attached to streams. 问题是您的读者附加到流。 As such, you are only expected to iterate through them once. 因此,您只需要迭代一次。 The next time you iterate through, it's already at end of file, so it doesn't find anything else (hence "the second loop doesn't execute"). 下次迭代时,它已经在文件末尾,因此它没有找到任何其他内容(因此“第二个循环不执行”)。

You can fix this by seek ing the fileobject back to the start each time you finish with it: 你可以解决这个问题通过寻求每次你用它完成时间荷兰国际集团的文件对象回到开始:

import os

for row in reader:
    user_ip=row['ip_address']
    print("LOOP 1 " + user_ip)

    for l_row in l_reader:
        lookup_ip=l_row['lookup_ip']
        print("LOOP 2 " + user_ip + lookup_ip)

    # I prefer to explicitly say where we're seeking from, though I 
    # could have just left it as seek(0).
    lookup_file_object.seek(0, os.SEEK_SET)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM