列表分配索引超出范围?

时间:2018-02-04 20:25:00

标签: python csv module

我使用CSV模块通过临时文件更新数据,直到我尝试创建新用户为止。我以前从未经历过这个错误,我也不知道它为什么会发生。

数据:

分数文件包含:

adam,0,5,4
bob,3,5,2
charlie,7,9,4
micheal,0,69,6

代码:

import csv
import os
from shutil import copyfile

name = input('Name: ')
score = int(input('Score: '))
found = False

open('temp9.csv','w').close()

with open('scores.csv','r') as data:
    read = csv.reader(data)
    for row in read:
        print(row)
        if row:
            if row[0] == name:
                found = True
                row[1] = row[2]
                row[2] = row[3]
                row[3] = score
                print('found')

            with open('temp9.csv','a') as temp:
                writer = csv.writer(temp)
                print('line =',[row[0],row[1],row[2],row[3]])
                writer.writerow([row[0],row[1],row[2],row[3]])

if found == False:
    with open('temp9.csv','a') as temp:
        row[0] = name
        row[1] = 0
        row[2] = 0
        row[3] = score

        writer = csv.writer(temp)
        print('line =',[row[0],row[1],row[2],row[3]])
        writer.writerow([row[0],row[1],row[2],row[3]])

os.remove('scores.csv')
copyfile('temp9.csv','scores.csv')

错误:

当我创建新用户时,会产生以下错误:

Traceback (most recent call last):
  File "C:/Users/Adam/Desktop/foo.py", line 35, in <module>
    row[0] = name
IndexError: list assignment index out of range

1 个答案:

答案 0 :(得分:2)

您可以大大简化(并纠正)您的循环,如:

代码:

with open('temp9.csv','a') as temp:
    row = [name, 0, 0, score]

    writer = csv.writer(temp)
    print('line =', row)
    writer.writerow(row)

解释

此:

row[0] = name
row[1] = 0
row[2] = 0
row[3] = score

不起作用,因为您之前没有将行定义为列表,因此您无法以这种方式添加行。

还有:

print('line =',[row[0],row[1],row[2],row[3]])

忽略了列表的要点,因为不需要通过每个元素访问列表只是为了转向并构建相同的列表。