Sara Sara - 2 months ago 9
Python Question

Copying some data of a file and pasting it to another file in python

I have a file, where I want to copy some data of the file and paste it to another file, for example suppose a file contains the following data:

AlphaforBravo007 102000000010170000000001 SusanaForCharlie 1000 end


From the above text I want to copy
102000000010170000000001
and
1000
respectively and paste it to a new file, each on new row.

I would really appreciate any hint.

Answer
with open('file1.txt') as f1,open('file2.txt','w') as f2:
 for line in f1: 
   x=line.split()   #now x is ['AlphaforBravo007', '102000000010170000000001', 'SusanaForCharlie', '1000', 'end']
   f2.write('\n'.join((x[1],x[3]))+'\n')

now file2.txt contains:

102000000010170000000001
1000