Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print names from a text file in Python

Tags:

python-3.x

I have got a text document that looks something like this

Kei 1 2 3 4 5
Igor 5 6 7 8 9
Guillem 8 7 6 9 5

How can I print their names and their last 3 scores

I came up with this

class_3 = open('class_3','r')
read = class_3.read()
read.split()
print(read)

But it came out with just

K

Please help

like image 822
Leighton Guang Avatar asked Feb 08 '23 05:02

Leighton Guang


1 Answers

You can loop over file object and split the lines, then use a simple indexing to print the expected output:

with open('example.txt') as f:
    for line in f:
        items = line.split()
        print items[0], ' '.join(items[-3:])

Output :

Kei 3 4 5
Igor 7 8 9
Guillem 6 9 5

The benefit of using with statement for opening the file is that it will close the file at the end of the block automatically.

As a more elegant approach you can also use unpacking assignment in python 3.X:

with open('example.txt') as f:
    for line in f:
        name, *rest = line.split()
        print(name, ' '.join(rest))
like image 164
Mazdak Avatar answered Feb 12 '23 10:02

Mazdak