0

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

1
  • first check if list is not empty and has length of 3 Commented Oct 21, 2019 at 16:12

2 Answers 2

1

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()
Sign up to request clarification or add additional context in comments.

Comments

0

you last lis is empty and you are trying to access lis[0]. check first that the list is not empty by if lis:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.