how two join and arrange two files together
__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',
> 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:
open_files = (open(f) for f in files if exits(f))
> 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.
More information about the Python-list