如何在Python中将文件读入2D数组?

时间:2017-03-09 22:41:11

标签: python arrays

所以我有一个包含此

的文件(user.txt)
James, 10, Orange 
Andrew, 16, Yellow 
Graham, 23, Pink

我想这样做,所以我可以将文件读入嵌套列表,这样我就可以了

print(user[0][1])
#10

我试过了:

with open("user.txt") as file:
    user = [line.split(", ") for line in file.readlines()]

print(user[0][1])

然而我得到'IndexError:列表索引超出范围'

希望有人可以提供帮助

1 个答案:

答案 0 :(得分:1)

with open("file location") as file:
    user = [line.rstrip("\n").split(", ") for line in file]