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
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With