Izento
Izento

Reputation: 119

Taking a word from a string inside another file

So, my problem is I am trying to separate lines in a text file, then separate each word into different objects, one being whole_name, and the other being score.

Example of text document:

Adam Smith 89
Dave Jones 70
John Doe 54
Jane Doe 96

Notice how each line is a different name followed by a score.

Here's the important part of the code I have which is failing:

for line in infile.readlines():
    objects = line.split(" ")
    whole_name = objects[0:2]

What this is giving me is the last name, Jane Doe and that's it. I don't know how to get the other names from the text file

Upvotes: 0

Views: 34

Answers (1)

Ionut Hulub
Ionut Hulub

Reputation: 6326

whole_names = list()
for line in infile.readlines():
    objects = line.split(" ")
    whole_names.append(' '.join(objects[0:2]))

You keep overwriting the whole_name variable hence you only get the last name. Make whole_names a list and append all names to it. This way at the very end, whole_names will be a list of strings containing all the names.

Upvotes: 1

Related Questions