Python compare bombs if files not sorted
Question: I have written some code to compare two files via a search string.

The file = master data file The checkfile = list of states & regions

When I have more than 1 state in the file that is not in sorted order it bombs
out.

How can i get this to work without having to sort my "file"

The Error message: Traceback (most recent call last): File
"./gangnamstyle.py", line 27, in csvLineList_2 = csv2[lineCount].split(",")
IndexError: list index out of range

My code:

    
    
    #!/usr/bin/python
    
    import csv
    file = raw_input("Please enter the file name to search: ") #File name
    checkfile = raw_input("Please enter the file with the search data: ") #datafile
    save_file = raw_input("Please enter the file name to save: ") #Save Name
    search_string = raw_input("Please type string to search for: ") #search string
    #row = raw_input("Please enter column text is in: ") #column number - starts at 0
    #ID_INDEX = row
    #ID_INDEX = int(ID_INDEX)
    f = open(file)
    f1 = open(save_file, 'a')
    csv1 = open(file, "r").readlines()
    csv2 = open(checkfile, "r").readlines()
    
    
    #what looks for the string in the file
    copyline=False
    for line in f.readlines():
     if search_string  in line:
      copyline=True
      if copyline:
        f1.write(line)
    
    for lineCount in range( len( csv1) ):
        csvLineList_1 = csv1[lineCount].split(",")
        csvLineList_2 = csv2[lineCount].split(",")
        if search_string == csvLineList_2[0]:
        f1.write(csvLineList_2[2])
    
    
    
    f1.close() #close saved file
    f.close() #close source file
    #csv1.close()
    #csv2.close()
    


Answer: OK, so that error message is an `IndexError: list index out of range` in the
line `csvLineList_2 = csv2[lineCount].split(",")`. There's only one indexing
happening there, so apparently `lineCount` is too big for csv2.

lineCount is one of the values of range(len(csv1)). That makes it
automatically in range for csv1. Apparently csv1 and csv2 are not the same
length, causing the IndexError.

Now that's quite possible, because they contain lines from different files.
Apparently the files don't have equal number of lines.

To be honest I have no clue why you are reading the lines into csv1 at all.
You loop over those lines and split them (into the variable `csvLineList_1`),
but you never use that variable.

I think your loop should just be:

    
    
    for line in csv2:
        parts = line.strip().split(",")  # line.strip() removes whitespace and the newline
                                         # at the end of the line
        if search_string == parts[0]:
            f1.write(parts[2] + "\n")  # Add a newline, you probably want it
    

I hope this helps.

