[Tutor] how to join two different files

wesley chun wescpy at gmail.com
Sat Jul 18 00:50:35 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. :-)

cheers,
-wesley

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)

myMac$ cat fileA.txt
FileA
12
15
18
20

myMac$ cat fileB.txt
FileB
14
16
18
20
22

myMac$ parafiles.py
FileA FileB
12 14
15 16
18 18
20 20

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
"Python Fundamentals", Prentice Hall, (c)2009
    http://corepython.com

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


More information about the Tutor mailing list