list index out of range error while reading csv file in python

前端 未结 1 1266
予麋鹿
予麋鹿 2021-01-25 06:56

I have this code where I am reading a csv file, using NamedTemporaryFile to change the contents of the csv file.

def update_localcsv():

    ping =          


        
1条回答
  •  囚心锁ツ
    2021-01-25 07:26

    I was able to reproduce the error you are seeing by adding a newline at the end of my CSV file. I have taken the liberty of editing your question accordingly.

    There are a few simple solutions. The most obvious would be to remove the trailing newline at the end of the file.

    An more robust would be to skip any empty rows, or rows that do not have the two columns you require. You would still probably want to pass them through to the output writer, so you could do this (print statements omitted):

    if len(row) == 2:
        row[0] = random.choice(ping)
        curr_time = datetime.datetime.time(datetime.datetime.now()).strftime('%I:%M %p')
        row[1] = str(curr_time)
    writer.writerow(row)
    

    If you want to remove empty lines, you can add a separate case for that:

    if row:
        writer.writerow(row)
    

    Since empty arrays are falsy, they will not be passed through.

    0 讨论(0)
提交回复
热议问题