在python中读取csv文件时列出索引超出范围错误 [英] list index out of range error while reading csv file in python

查看:355
本文介绍了在python中读取csv文件时列出索引超出范围错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在读取csv文件的地方有此代码,使用NamedTemporaryFile更改了csv文件的内容.

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 = ["Yes","No"]
    filename = 'file1.csv'
    tempfile = NamedTemporaryFile(mode= 'w',delete=False)

    with open(filename, 'rt') as csvFile, tempfile:
        reader = csv.reader(csvFile, delimiter=',', quotechar='"')
        writer = csv.writer(tempfile, delimiter=',', quotechar='"')

        for row in reader:

            print(row)
            row[0] = random.choice(ping)

            curr_time = datetime.datetime.time(datetime.datetime.now()).strftime('%I:%M %p')
            row[1] = str(curr_time)
            print('current time: '+str(curr_time))
            print("New ping status = " + str(row))
            writer.writerow(row)

    shutil.move(tempfile.name, filename)

运行此代码时,我可以看到print(row)打印['Yes', '04:23 PM'],但随后在row[0] = random.choice(ping)处抛出IndexError: list assignment index out of range错误.

When I run this code I can see print(row) printing ['Yes', '04:23 PM'] but then it throws IndexError: list assignment index out of range error at row[0] = random.choice(ping).

这是我的csv文件中的当前内容:

This is the current content in my csv file:


Yes,04:23 PM

为什么会出现此错误?

注意::当我执行print(type(row))时,会得到<class 'list'>.我还看到一个空行正在打印:

NOTE: When I do print(type(row)) I get <class 'list'>. I also see an empty row getting printed:

['Yes', '04:23 PM']
current time: 05:03 PM
New ping status = ['Yes', '05:03 PM']
[]

推荐答案

我能够通过在CSV文件的末尾添加换行符来重现您看到的错误.我已自由地相应地编辑您的问题.

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.

这篇关于在python中读取csv文件时列出索引超出范围错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆