How to print names from a text file in Python -


i have got text document looks this

kei 1 2 3 4 5 igor 5 6 7 8 9 guillem 8 7 6 9 5 

how can print names , last 3 scores

i came this

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

but came out just

k 

please help

you can loop on file object , split lines, use simple indexing print expected output:

with open('example.txt') f:     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 opening file close file @ end of block automatically.

as more elegant approach can use unpacking assignment in python 3.x:

with open('example.txt') f:     line in f:         name, *rest = line.split()         print(name, ' '.join(rest)) 

Comments

Popular posts from this blog

html - Styling progress bar with inline style -

java - Oracle Sql developer error: could not install some modules -

How to use autoclose brackets in Jupyter notebook? -