[Tutor] how to join two different files

wesley chun wescpy at gmail.com
Thu Jul 30 10:06:33 CEST 2009

>> Maybe you could break that up a bit? This is the tutor list, not a
>> one-liner competition!
> rather than one-liners, we can try to create the most "Pythonic" solution. below's my entry. :-)
> myMac$ cat parafiles.py
> #!/usr/bin/env python
> from itertools import izip
> from os.path import exists
> def parafiles(*files):
>    vec = (open(f) for f in files if exists(f))
>    data = izip(*vec)
>    [f.close() for f in vec]
>    return data
> for data in parafiles('fileA.txt', 'fileB.txt'):
>    print ' '.join(d.strip() for d in data)

i proposed this problem as a code golfing competition to my
co-workers, and after tweaking it slightly to take filenames from the
command-line instead of as function parameters, i reduced my original
solution to:

from itertools import izip
from os.path import exists
from sys import argv

vec = (open(f) for f in argv[1:] if exists(f))
for d in izip(*vec):
    print ' '.join(c.strip() for c in d)
for f in vec:

if this was a code golf competition, and i was more careless about
leaking filehandles (or letting Python deal with it), i can actually
reduce it to an ugly (yet elegant) 1-liner serving as an example of
how *not* to code in production:

print '\n'.join(' '.join(c.strip() for c in d) for d in izip(*(open(f)
for f in argv[1:] if exists(f))))

note that the only list used here is sys.argv (using map() or
[listcomp] creates lists which use memory... superfluous if only
iterating across them once). anyway, please don't try this at work
folks. :-)

-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Python Web Development with Django", Addison Wesley, (c) 2009

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca

More information about the Tutor mailing list