joining two column
Tim Chase
python.list at tim.thechases.com
Fri May 14 14:46:55 EDT 2010
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
More information about the Python-list
mailing list