Python: Use one list to search another list and pull corresponding rows
Question: I am stuck. I have a list of strings, and I want to search through a bigger
list that has additional columns associated with those strings, and put the
strings from my first list into a new file with their associated values from
the second list (ie. take the whole row where there is a string match).

This is what I have so far

    
    
    from sys import argv
    
    script, filename, filename2, outputfile = argv
    
    import csv #program to help manipulate csv files
    with open(filename,'rU') as fin1, open(filename2, 'rU') as fin2, open (outputfile,'w') as fout: #simplifies opening and closing a file into one line
    
    for row in fin1:
        gene = row[0]
    
    writer = csv.writer(fout, delimiter=',')       #dialect must be specified, csv file so it is a ,
        for gene in csv.reader(fin1, delimiter=','):
            for row in csv.reader(fin2, delimiter=','):
                if gene == row[4]: 
                    writer.writerow(row)
                    break
    

Thank you


Answer: 
    from sys import argv
    
    script, filename, filename2, outputfile = argv
    
    import csv # program to help manipulate csv files with open(filename,'rU') as fin1, open(outputfile,'w') as fout:  # simplifies opening and closing a file into one line
        writer = csv.writer(fout, delimiter=',')       # dialect must be specified, csv file so it is a ,
        for row_fin1 in csv.reader(fin1, delimiter=','):
            gene = row_fin1[0]
            with open(filename2, 'rU') as fin2:
                for row_fin2 in csv.reader(fin2, delimiter=','):
                    if gene == row_fin2[4]:
                        writer.writerow(row_fin2)
                        break
    

You need to open and close the fin2 each time, because csv reader reads only
in forward direction and cant go back. Hope this helps.

