[Tutor] Fwd: swapping lines between files
Kent Johnson
kent37 at tds.net
Tue Mar 24 22:35:05 CET 2009
Forwarding to the list
---------- Forwarded message ----------
From: Bala subramanian <bala.biophysics at gmail.com>
Date: Tue, Mar 24, 2009 at 11:23 AM
Subject: Re: [Tutor] swapping lines between files
To: Kent Johnson <kent37 at tds.net>
Hai Kent,
Thank you. I tried the same zip with a list and a file, instead of
just two files. It works fine. But now i am stuck in overwriting the
input file with value.
What i want to do ?
I have 3 files
file 1 file2 file3
1 20.22 22 22.22 56 66.77
2 21.24 20 34.56 44 66.55
3 33.33 22 35.77 22 45.66
Now i have a list
all =[ [5,10,13], [44,56,77], [55,67,78]]
file 1 file 2 file 3
5 20.22 44 22.22 55 66.77
10 21.24 56 34.56 67 66.55
13 33.33 77 35.77 78 45.66
I am replacing the first position in file with the values in the list.
The following worked for me,
rmsd=argv[1:]
for n in range(3):
infile=open(rmsd[n])
for x, y in zip(all[n],infile):
yitem=y.split()
yitem[0]=str(x)
print yitem
But now i simply want to overwrite the input files. I am stuck here
because when i create a filelist like the following,
file_list=FileInput(rmsd,inplace=1)
print file_list
<fileinput.FileInput instance at 0x85bdb6c>
Now file_list is not a list to loop but a fileinput object, so i am
stuck in looping this and my list all simultaneously.
Bala
On Mon, Mar 23, 2009 at 6:42 PM, Kent Johnson <kent37 at tds.net> wrote:
>
> 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