Leighton Guang
Leighton Guang

Reputation: 43

How to print names from a text file in Python

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

Upvotes: 4

Views: 1938

Answers (2)

Kasravnd
Kasravnd

Reputation: 107337

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))

Upvotes: 7

Igor
Igor

Reputation: 1292

In python 3.x you will have to change @Kasramvd's answer slightly. You have to add parenthesis around the parameters of the call to the print function.

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

Upvotes: 1

Related Questions