want to read rows from a csv file and turn them into lists my code >> list 0 = [] list 1 = [] list 2 = [] list 3 = [] list 4 = [] list 5 = [] with open('all_plans2.csv', 'rb') as csvfile: myreader = csv.reader(csvfile) # for row in myreader: # print ', '.join(row) count = 0 for row in myreader: print count count += 1 listcount =rowcount this prints 0 1 2 3 4 5 so I have 6 rows in the csv that I would like to manipulate as 6 lists:(list0, list1, ...)
What happens if you print row?
The first lines list 0 =[] produce errors when I try them. The import csv is missing. The listcount=rowcount row gives an error because they are not used at all other than that line. The program above if all were working would print exactly what you ask it to, the integer variable count. Since there are 6 rows it would print the integers fro 0 to 6 not including 6. Below is an example that uses a list of list and a dictionary of lists. Which would be easier and much better than using separate list variables, and will work with any number of lines without adding more variables. import csv # initialize list rows1 = [] # initialize dictionary rows2 = {} with open('f:/test.csv', 'rb') as csvfile: myreader = csv.reader(csvfile) count = 0 for row in myreader: # add row as list to list rows1.append(row) # add row as list to dictionary rows2[count] = row count += 1 print rows1 print print rows2
Thank you, that's what i needed. I appreciate you taking the time to help me.
Join our real-time social learning platform and learn together with your friends!