0

I have a text file formatted as shown, and i'm trying to split each line up into two variables, however, for any other than the first block of code that is read I get a "list index out of range" error.

file = open("trying to get this to work.txt", "r")
user5 = line.readlines()[4]
field5 = user5.split(",")
name5 = field5[0]
score5 = field5[1]

user4 = file.readlines()[3]
field4 = user4.split(",")
name4 = field4[0]
score4 = field4[1]

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

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

user1 = file.readlines()[0]
field1 = user1.split(",")
name1 = field1[0]
score1 = field1[1]
file.close()

Text file:

Jake,70
Jack,60
Jill,50
James,20
Janet,10

eg. it will give me the error for:

user4 = file.readlines()[3]

but no for

user5 = file.readlines()[4]

I know that this isn't the most elequent way to program what I want to do, but to me it seems like it should still work. Any help is greatly appreciated :)

  • Does this answer your question? https://stackoverflow.com/questions/16374425/python-read-function-returns-empty-string/16374481 – jfaccioni Feb 28 '20 at 16:47

2 Answers2

0

Try out this one. Read file and store value in users_list -> users_list = file.readlines()

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()
krishna
  • 1,029
  • 6
  • 12
0

This will store the result desired in a dictionary with the key being the user's name and the value being the score.

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)

The resultant dictionary is {'Jake': '70', 'Jack': '60', 'Jill': '50 ', 'James': '20', 'Janet': '10'}

Gerry P
  • 7,662
  • 3
  • 10
  • 20