JayGatz
JayGatz

Reputation: 271

Keep last word on each line of text file, delete rest

I wrote this python script that keeps the first word on each line in a text file and then deletes the rest.

How can I do the opposite, kind of, meaning keep the last word on each line in the file and delete all the words and spaces before it?

import sys
with open(sys.argv[1]) as f, open('out.txt', 'w') as out:
     for line in f:
         out.write(line.split()[0]+'\n')

so if a line in the given file was "out there somewhere" all that would be kept and written to out.txt on that line would be "somewhere".

Upvotes: 3

Views: 2722

Answers (1)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250961

use line.split()[-1] to get the last word.

Python supports negative indexing:

>>> lis = [1, 2, 3, 4, 5]
>>> n = 1
>>> lis[-n]
5
>>> lis[len(lis) - n] # equivalent to lis[-n] 
5

Your code:

import sys
with open(sys.argv[1]) as f, open('out.txt', 'w') as out:
     for line in f:
         out.write(line.split()[-1]+'\n')

Upvotes: 2

Related Questions