简体   繁体   English

列表分配索引超出范围?

[英]List assignment index out of range?

I'm using the CSV module to update data via temporary files, it works until I try to create a new user. 我正在使用CSV模块通过临时文件更新数据,该模块在尝试创建新用户之前一直有效。 I have never experienced this error before and I have no understanding as to why it has occurred. 我以前从未遇到过该错误,也不清楚为什么会发生。

Data: 数据:

The scores file contains: 分数文件包含:

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

Code: 码:

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

Error: 错误:

When I create a new user it creates the following error: 当我创建一个新用户时,它会产生以下错误:

 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 

You can greatly simplify (and correct) your loop like: 您可以大大简化(并更正)循环,例如:

Code: 码:

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

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

Lists: 清单:

This: 这个:

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

Does not work because you have not previously defined row as a list, so you cannot add to it in this way. 不起作用,因为您之前没有将行定义为列表,因此无法以这种方式添加到列表中。

Also this: 还有这个:

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

misses the point of a list, in that the list does not need to be accessed via each element just to turn around and build the same list. 遗漏了列表的要点,因为不需要通过每个元素来访问列表,而只是转过头来构建相同的列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM