joining two column

Tim Chase python.list at tim.thechases.com
Sat May 15 10:40:15 EDT 2010


On 05/15/2010 09:20 AM, mannu jha wrote:

BTW: your mailer makes an absolute mess of plain-text emails, 
putting multiple spaces



between


every


single


line


which


makes


it


very


hard


to


read.

Please fix it, use a real mailer, or risk getting ignored (or 
worse, plonked).  Fortunately, Vim makes it modestly easy to 
unmung the rubbishy format.

 >>    # 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
 >
 > 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

That's because you're not importing itertools, but you're just 
importing "chain" from within it.  So of course when you try to 
use "itertools.izip", itertools doesn't exist.  You can either use

   import itertools
   #...
   for left, right in itertools.izip(f1,f2):

or

   from itertools import izip
   #...
   for left, right in izip(f1,f2):

-tkc







More information about the Python-list mailing list