Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将部分文本文件保存为变量时,列表索引超出范围_Python_Python 3.x - Fatal编程技术网

Python 将部分文本文件保存为变量时,列表索引超出范围

Python 将部分文本文件保存为变量时,列表索引超出范围,python,python-3.x,Python,Python 3.x,我有一个文本文件,格式如图所示,我试图将每一行分成两个变量,但是,对于读取的第一个代码块以外的任何代码块,我都会得到一个“列表索引超出范围”错误 文本文件: Jake,70 Jack,60 Jill,50 James,20 Janet,10 它会给我以下方面的错误: user4 = file.readlines()[3] 但对我来说不是 user5 = file.readlines()[4] 我知道这不是最有效的编程方式,但对我来说,它似乎仍然可以工作。非常感谢您的帮助:)试试这个。读取文

我有一个文本文件,格式如图所示,我试图将每一行分成两个变量,但是,对于读取的第一个代码块以外的任何代码块,我都会得到一个“列表索引超出范围”错误

文本文件:

Jake,70
Jack,60
Jill,50
James,20
Janet,10
它会给我以下方面的错误:

user4 = file.readlines()[3]
但对我来说不是

user5 = file.readlines()[4]

我知道这不是最有效的编程方式,但对我来说,它似乎仍然可以工作。非常感谢您的帮助:)

试试这个。读取文件并将值存储在用户列表中


这将在字典中存储所需的结果,键为用户名,值为分数

import os
user_dict={}
f_path=os.path.join(r'c:\Temp', 'testfile.txt')# path to the file
with open(f_path, "r") as file:
    users = file.readlines()
for user in users:
    user_info=user.split(',')
    name=user_info[0]
    value=user_info[1].rstrip('\n')# strip of the \n
    user_dict[name]=value
print (user_dict)
生成的字典是
{'Jake':'70','Jack':'60','Jill':'50','James':'20','Janet':'10'}

这能回答你的问题吗?
file = open("test.txt", "r")
users_list = file.readlines()

user5= users_list[4]
field5 = user5.split(",")

name5 = field5[0]
score5 = field5[1]
user4 = users_list[3]
field4 = user4.split(",")
name4 = field4[0]
score4 = field4[1]

user3 = users_list[2]
field3 = user3.split(",")
name3 = field3[0]
score3 = field3[1]

user2 = users_list[1]
field2 = user2.split(",")
name2 = field2[0]
score2 = field2[1]

user1 = users_list[0]
field1 = user1.split(",")
name1 = field1[0]
score1 = field1[1]
file.close()
import os
user_dict={}
f_path=os.path.join(r'c:\Temp', 'testfile.txt')# path to the file
with open(f_path, "r") as file:
    users = file.readlines()
for user in users:
    user_info=user.split(',')
    name=user_info[0]
    value=user_info[1].rstrip('\n')# strip of the \n
    user_dict[name]=value
print (user_dict)