how two join and arrange two files together

Peter Otten __peter__ at web.de
Sat Jul 18 05:17:33 EDT 2009


amrita at iisermohali.ac.in wrote:

> I tried to join these two files together using command.......
> 
> 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('/home/amrita/alachems/chem1.txt',
> '/home/amrita/secstr/secstr.txt'):
>     print ' '.join(d.strip() for d in data)

parafiles has a bug: vec is a generator and hence cannot be run twice. 
Therefore the odd [f.close()...] list comprehension (don't use a list comp 
if you don't care about the result!) has no effect. 

If you change vec into a list you will be hit by another problem -- the for 
loop trying to operate on closed files. While the correct approach probably 
involves a contextlib.contextmanager I recommend that you concentrate on 
your real problem and keep parafiles() simple:

def parafiles(*files):
    open_files = (open(f) for f in files if exits(f))
    return izip(*open_files)

> it just joined the column of two files.

Can you make an effort to express clearly what you want, preferrably with a 
simple and unambiguous example?

Please keep the line widths below the threshold of 78 characters to avoid 
messing it up on its way to the reader.

Peter




More information about the Python-list mailing list