Reading data from 2 different files and writing to a single file

Wolfgang Maier wolfgang.maier at
Mon Jan 28 16:08:38 CET 2013

as many others I am not exactly sure what the purpose of your code really
However, if what you´re trying to do here is to take one line from f1, one
line from f2 and then write some combined data to nf, it is not surprising
that you're not getting what you expect (the main reason being that your for
loops are nested, as pointed out already).
In that case, a much cleaner and less error-prone solution would be
iterator-zipping, leaving you with just one for loop that is easy to

for l,s in zip(f1,f2):
	# now l holds the next line from f1, s the corresponding line from

if your files are large, then in python 2.x you should use:

import itertools
for l,s in itertools.izip(f1,f2):

The reason for this is that before python 3 zip gathered and returned your
results as an in-memory list. itertools.izip and the built-in python 3 zip
return iterators.

Hope that helps,

From: inshu chauhan [mailto:insideshoes at] 
Sent: Monday, January 28, 2013 2:32 PM
To: python-list at
Subject: Reading data from 2 different files and writing to a single file

In the code below I am trying to read 2 files f1 and f2 , extract some data
from them and then trying to write them into a single file that is 'nf'.

import cv
f1 = open(r"Z:\modules\Feature_Vectors_300.arff")
f2 = open(r"Z:\modules\Feature_Vectors_300_Pclass.arff")
nf = open(r"Z:\modules\trial.arff", "w")

for l in f1:
    sp = l.split(",")
    if len(sp)!= 12:
        ix = sp[0].strip()
        iy = sp[1].strip()
        print ix, iy
       for s in f2:
            st = s.split(",")
            if len(st)!= 11:
                clas = st[10].strip()
             print ix, iy, clas
             print >> nf, ix, iy, clas


I think my code is not so correct , as I am not getting desired results and
logically it follows also but I am stuck , cannot find a way around this
simple problem of writing to a same file.. Please suggest some good pythonic
way I can do it.. 

Thanks in Advance 

More information about the Python-list mailing list