简体   繁体   English

从CSV读取时,Python错误列表索引超出范围

[英]Python error list index out of range when reading from CSV

Hey I am trying to read data from a list that is from a CSV file 嘿,我试图从CSV文件的列表中读取数据

def Load(): #Loads data from the csv that can be stored in functions
global userdata
global user
userdata = []
f = open('userdata.csv','r')
data = csv.reader(f)
for row in data:
    user = []
    for field in row:
        user.append(field)
    userdata.append(user)
f.close()

This is the login function which I am looping over 这是我正在遍历的登录功能

def Login(): #Login function
global userdata
Load()
global user
print('Please now login to your account')

x = False
while x == False:
    usernameLog = input('Please enter your username: ')

    j = len(userdata)
    for i in range(0,j):
        if usernameLog == userdata [i][0]: #Validates username
            print('Username accepted')

            time.sleep(1)

My program successfully writes to the CSV but just doesn't read from it without throwing out this error. 我的程序已成功写入CSV,但只有在不抛出此错误的情况下才从中读取。 I might just be being stupid though. 我可能只是愚蠢。

You have the line user = [] inside the for loop, so you are always "cleaning" user before appending the new value, so only the last value is added, and the previous one is removed. 您在for循环中有user = []行,因此在附加新值之前,您总是“清理”用户,因此仅添加最后一个值,并删除前一个值。

You should take it out of the loop, the same you are doing with userdata. 您应该将其带出循环,就像处理userdata一样。

(This is what it looks like, unless your csv structure is totally different and you don't need one user per one userdata) (这就是它的样子,除非您的csv结构完全不同,并且您不需要每个用户数据一个用户)

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

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