python 读csv报错_在python中读取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)

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).

This is the current content in my csv file:

Yes,04:23 PM

Why is this error coming?

NOTE: When I do print(type(row)) I get . I also see an empty row getting printed:

['Yes', '04:23 PM']

current time: 05:03 PM

New ping status = ['Yes', '05:03 PM']

[]

解决方案

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值