Reputation: 101
This is simple program of reading the csv file in form of list, Program is able to print as per index but at last there is a index error
import csv
with open('file.csv','r') as f:
reader = csv.reader(f)
for r in reader:
lis = list(r)
print (lis)
file_dat = lis[0]
file_no = lis[1]
content = lis[2]
print (file_dat)
print ("File Data Read Successful")
f.close()
and the output i get of this program is
['ASFDASD', '2019-10-19', 'horse']
ASFDASD
File Data Read Successful
[]
Traceback (most recent call last):
File "C:\Users\KIRA\AppData\Local\Programs\Python\Python37-32\direction.py", line 14, in <module>
file_dat = lis[0]
IndexError: list index out of range
Upvotes: 0
Views: 241
Reputation: 5745
you last lis is empty and you are trying to access lis[0].
check first that the list is not empty by if lis:
Upvotes: 0
Reputation: 5059
Looks like your code is reading the last line of the input file as a completely empty line, resulting in an empty list. This empty list is printed out right below File Data Read Successful
.
Maybe check to make sure the list isn't empty after you print it but before you assign it?
import csv
with open('file.csv','r') as f:
reader = csv.reader(f)
for r in reader:
lis = list(r)
if(lis.len() = 3):
print (lis)
file_dat = lis[0]
file_no = lis[1]
content = lis[2]
print (file_dat)
print ("File Data Read Successful")
f.close()
Upvotes: 1