Filter it
No one wants to browse a 1,000 plus lines list. We need to show only what the user wants to see.
In this example the program asks for a word (line 10). If the word is not found in the read line (line 23) the program skips that line and restarts the loop, therefore showing only the lines containing the typed word.
But there is a problem. If we type "mercedes" the program will find nothing since all the words in the file are upper case. To make it case insensitive we use the upper() method (line 16) to make any typed word into upper case.
1:import csv 2: 3:cars_file = open('2006_FE_Guide_14-Nov-2005_download.csv', 'r') 4:reader = csv.reader(cars_file) 5: 6:i = 0 # line counter 7:message = "Hit Enter to continue or any other char followed by Enter to stop: " 8: 9:print 10:word = raw_input("Type the word you want to filter the list on: ") 11:print 12: 13:# If we type a word in lower case it will not 14:# be found since the whole file is in upper case 15:# so we turn the word into upper case 16:word = word.upper() 17: 18:reader.next() 19:for line in reader: 20: 21: # if the line does not contain the typed word 22: # then continue to the next line 23: if ''.join(line).find(word) == -1: 24: continue 25: 26: i = i + 1 27: 28: print line[1], 29: print line[2], 30: print line[3], 31: print line[5], 32: print "average mpg is", line[9] 33: 34: if i == 10: 35: 36: i = 0 37: print 38: 39: char = raw_input(message) 40: if char != '': # if char is not empty 41: break 42: 43: print 44: 45:print 46:cars_file.close()Type "MeRcEdEs" and it will find all lines with "MERCEDES". The line 23 uses two string methods: join() and find(). The former joins all items in the list of columns into one only string so the later can look for the word in it.