The code worked when i initially put it in but then i added more late on and it started giving me this indexerror on index 0 when trying to load a cvs file. im trying to put the left most value in the first list and the right most value of each row in the csv file in the second list. it works when i manualy input the values but not when i input the values from a program
import csv
list1 = []
list2 = []
with open('file.csv') as f:
f.readline()
csvin = csv.reader(f)
for row in csvin:
list1.append(row[0])
list2.append(row[1])
header1,header2
l1value,l2value
l1value,l2value
Error message:
list1.append(row[0])
IndexError: list index out of range
Your code like it is posted works fine.
Using the readline()
function to skip the header line is ok.
Your csv file appears to contain blank lines which cause the error message as csv.reader
returns a blank line as en empty list.
with open(filename) as f:
f.readline()
csvin = csv.reader(f)
for row in csvin:
print(row)
# returns the following rows:
# ['1', '3']
# ['2', '4']
# []
To avoid this you can either check your csv file to not contain blank lines or add an if condition
to check for an empty row by checking row:
l, r = [], []
with open(filename) as f:
f.readline()
csvin = csv.reader(f)
for row in csvin:
if row:
l.append(row[0])
r.append(row[1])