[Tutor] swapping lines between files
Kent Johnson
kent37 at tds.net
Mon Mar 23 18:42:43 CET 2009
On Mon, Mar 23, 2009 at 12:39 PM, Bala subramanian
<bala.biophysics at gmail.com> wrote:
> Dear Friends,
>
> Thanks for your replies for my previous mail.
>
> I have two files as follows.
>
> file 1 file2
> 200 1 3.55
> 210 2 4.55
> 242 3 1.22
> 248 4 3.10
> 256 5 1.11
>
> Now i have to replace 1,2,3,4,5 in file 2 with 200,210,242,248,256 in file1.
> Simply replacing position 1 in file2 with values in file1. Can i do it with
> zip function, if yes how to do it. Here both files contain same number of
> lines.
You can use zip() to combine the lines of the files. itertools.izip()
might be a better choice because it doesn't read the entire file at
once. Something like this (untested):
from itertools import izip
file2 = open(...)
out = open(..., 'w') # output file
for line1, line2 in izip(file1, file2):
# now create a line that merges the two and write it
line1 = line1.strip() # remove newline
line2items = line2.split()
line2items[0] = line1
newLine = '\t'.join(line2items)
out.write(newLine)
out.write('\n')
out.close()
Kent
More information about the Tutor
mailing list