我正在使用 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
最佳答案
您可以极大地简化(并纠正)您的循环,例如:
代码:
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]])
错过了列表的要点,因为列表不需要通过每个元素来访问,只是为了转身并构建相同的列表。
关于python - 列表分配索引超出范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48612655/