<br />
<br />
On Sat, 15 May 2010 00:14:05 +0530 wrote<br />
>On 05/14/2010 12:55 PM, James Mills wrote:<br />
<br />
>> file1:<br />
<br />
>> a1 a2<br />
<br />
>> a3 a4<br />
<br />
>> a5 a6<br />
<br />
>> a7 a8<br />
<br />
>><br />
<br />
>> file2:<br />
<br />
>> b1 b2<br />
<br />
>> b3 b4<br />
<br />
>> b5 b6<br />
<br />
>> b7 b8<br />
<br />
>><br />
<br />
>> and I want to join them so the output should look like this:<br />
<br />
>><br />
<br />
>> a1 a2 b1 b2<br />
<br />
>> a3 a4 b3 b4<br />
<br />
>> a5 a6 b5 b6<br />
<br />
>> a7 a8 b7 b8<br />
<br />
><br />
<br />
> This is completely untested, but this "should" (tm) work:<br />
<br />
><br />
<br />
> from itertools import chain<br />
<br />
><br />
<br />
> input1 = open("input1.txt", "r").readlines()<br />
<br />
> input2 = open("input2.txt", "r").readlines()<br />
<br />
> open("output.txt", "w").write("".join(chain(input1, input2)))<br />
<br />
<br />
<br />
I think you meant izip() instead of chain() ... the OP wanted to <br />
<br />
be able to join the two lines together, so I suspect it would <br />
<br />
look something like<br />
<br />
<br />
<br />
# OPTIONAL_DELIMITER = " "<br />
<br />
f1 = file("input1.txt")<br />
<br />
f2 = file("input2.txt")<br />
<br />
out = open("output.txt", 'w')<br />
<br />
for left, right in itertools.izip(f1, f2):<br />
<br />
out.write(left.rstrip('rn'))<br />
<br />
# out.write(OPTIONAL_DELIMITER)<br />
<br />
out.write(right)<br />
<br />
out.close()<br />
<br />
<br />
<br />
This only works if the two files are the same length, or (if <br />
<br />
they're of differing lengths) you want the shorter version. The <br />
<br />
itertools lib also includes an izip_longest() function with <br />
<br />
optional fill, as of Python2.6 which you could use instead if you <br />
<br />
need all the lines<br />
<br />
<br />
<br />
-tkc<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
-- <br />
<br />
with this <br />
from itertools import chain<br />
# OPTIONAL_DELIMITER = " "<br />
f1 = file("input1.txt")<br />
f2 = file("input2.txt")<br />
out = open("output.txt", 'w')<br />
for left, right in itertools.izip(f1, f2):<br />
out.write(left.rstrip('rn'))<br />
# out.write(OPTIONAL_DELIMITER)<br />
out.write(right)<br />
out.close()<br />
<br />
it is showing error:<br />
ph08001@linux-af0n:~> python join.py<br />
Traceback (most recent call last):<br />
File "join.py", line 6, in <module><br />
for left, right in itertools.izip(f1, f2):<br />
NameError: name 'itertools' is not defined<br />
ph08001@linux-af0n:~><br />
<br />
<br />
<br />