简体   繁体   English

将数据从 txt 文件传输到数组(列表索引超出范围)

[英]transfering data from txt file to an array (list index out of range)

I am have issues witch transfering data from my text file into my array.我在将数据从我的文本文件传输到我的数组时遇到问题。 As when i try to put data from the text file into the array it comes up with a list index out of range error.当我尝试将文本文件中的数据放入数组时,它会出现列表索引超出范围错误。 I just need a simple way of transfering a username and password into 2 different arrays.我只需要一种将用户名和密码传输到 2 个不同数组的简单方法。

username = []
password = []

lr = open("login.txt","r")
loginr = "temp"
  while loginr!="":
    loginr = lr.readline()
    field = loginr.split(",")
    username.append(field[0])
    password.append(field[1])
print(username+password)
lr.close()

The text file is layed out as文本文件布局为

simple,123,
legit,scary,
smite,Oxygen31,

You need to make sure that login.txt file has all the lines with username,password, .您需要确保login.txt文件的所有行都包含username,password, Other than that, I would recommend using with open() instead of open() and close() and then you can loop through the lines of the file object or use list comprehension to extract usernames and passwords.除此之外,我建议使用with open()而不是open()close()然后你可以遍历文件对象的行或使用列表理解来提取用户名和密码。 For example:例如:

# loop approach
with open('login.txt', 'r') as f:
    username = []
    password = []    
    for line in f:
        line = line.split(',')
        username.append(line[0])
        password.append(line[1])

# list comprehension approach
with open('login.txt', 'r') as f:
    data = [line.split(',') for line in f]
    username = [x[0] for x in data]
    password = [x[1] for x in data]

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

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