[Tutor] Files Merging

eryksun eryksun at gmail.com
Thu Oct 11 14:30:28 CEST 2012


On Thu, Oct 11, 2012 at 7:13 AM, Sunil Tech <sunil.techspk at gmail.com> wrote:
>
> text1 contains
> This is from Text1 --- 1st line
> ....
>
> text2 contains
> This is from Text2 --- 1st line
> ....
>
> i want result in text3 like
> This is from Text1 --- 1st line
> This is from Text2 --- 1st line
> ....
> but condition is "should not use any loops"

Use itertools.zip_longest() and itertools.chain.from_iterable(), along
with the text3.writelines(). zip_longest allows the files to be of
different lengths. zip would terminate at the shortest number of
lines, but fillvalue of zip_longest supplies a default value (set to
an empty string). chain.from_iterable joins the tuples from
zip_longest as one iterable to use as an argument to  writelines().
This way there are no pure Python loops, or even generator
expressions/comprehensions.


More information about the Tutor mailing list