Re: Re: joining two column
mannu jha
mannu_0523 at rediffmail.com
Sat May 15 10:20:34 EDT 2010
On Sat, 15 May 2010 00:14:05 +0530 wrote
>On 05/14/2010 12:55 PM, James Mills wrote:
>> file1:
>> a1 a2
>> a3 a4
>> a5 a6
>> a7 a8
>>
>> file2:
>> b1 b2
>> b3 b4
>> b5 b6
>> b7 b8
>>
>> and I want to join them so the output should look like this:
>>
>> a1 a2 b1 b2
>> a3 a4 b3 b4
>> a5 a6 b5 b6
>> a7 a8 b7 b8
>
> This is completely untested, but this "should" (tm) work:
>
> from itertools import chain
>
> input1 = open("input1.txt", "r").readlines()
> input2 = open("input2.txt", "r").readlines()
> open("output.txt", "w").write("".join(chain(input1, input2)))
I think you meant izip() instead of chain() ... the OP wanted to
be able to join the two lines together, so I suspect it would
look something like
# OPTIONAL_DELIMITER = " "
f1 = file("input1.txt")
f2 = file("input2.txt")
out = open("output.txt", 'w')
for left, right in itertools.izip(f1, f2):
out.write(left.rstrip('\r\n'))
# out.write(OPTIONAL_DELIMITER)
out.write(right)
out.close()
This only works if the two files are the same length, or (if
they're of differing lengths) you want the shorter version. The
itertools lib also includes an izip_longest() function with
optional fill, as of Python2.6 which you could use instead if you
need all the lines
-tkc
--
with this
from itertools import chain
# OPTIONAL_DELIMITER = " "
f1 = file("input1.txt")
f2 = file("input2.txt")
out = open("output.txt", 'w')
for left, right in itertools.izip(f1, f2):
out.write(left.rstrip('\r\n'))
# out.write(OPTIONAL_DELIMITER)
out.write(right)
out.close()
it is showing error:
ph08001 at linux-af0n:~> python join.py
Traceback (most recent call last):
File "join.py", line 6, in
for left, right in itertools.izip(f1, f2):
NameError: name 'itertools' is not defined
ph08001 at linux-af0n:~>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100515/588dc87d/attachment-0001.html>
More information about the Python-list
mailing list