Search code examples
pythonpython-2.7csvnested-loops

Python nested for loop to match strings from a text file to strings in a csv file


The purpose of my code is to read text file, add the lines into an array, iterate over each element in the array, convert the element to a string, and return lines from csv file that contain this string. My code is:

#Read cvs File from url
import csv
import urllib2   
url = 'mycsvfile.csv'
response = urllib2.urlopen(url)
cr = csv.reader(response)

#Read txt File
import linecache
fileName = 'myfile.txt'
myFile = open(fileName,'r')
list_of_lists = []
try:
    for line in myFile:
        list_of_lists.append(line.strip())

    #Lookup Lines
    for element in list_of_lists:
        elementstring=''.join(element)
        for row in cr:
            if elementstring in row:
                print row


finally:
    myFile.close()

The code does not display anything.


Solution

  • My guess is that in the first iteration of the csv reader you do not have any rows that satisfy the condition - if elementstring in row: (for the first elementstring ) . After this iteration, you have exhausted your csv and it has reached the end, trying to iterate over it again does not work.

    Try openning the url and csv outside the loop and convert each inner row into a set and then add them all into a list, and then use that to loop -

    #Read cvs File from url
    import csv
    import urllib2   
    url = 'mycsvfile.csv'
    response = urllib2.urlopen(url)
    cr = csv.reader(response)
    csvset = [set(i) for i in cr]
    
    #Read txt File
    import linecache
    fileName = 'myfile.txt'
    myFile = open(fileName,'r')
    list_of_lists = []
    try:
        for line in myFile:
            list_of_lists.append(line.strip())
    
        #Lookup Lines
        for element in list_of_lists:
            elementstring=''.join(element)
            for row in csvset:
                if elementstring in row:
                    print row
    
    
    finally:
        myFile.close()