oneclick
oneclick

Reputation: 101

Index error of CSV List in Python, even after getting output

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

Answers (2)

Lior Cohen
Lior Cohen

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

Nick Reed
Nick Reed

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

Related Questions