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

Dave Angel davea at davea.name
Mon Jan 28 15:05:25 CET 2013


On 01/28/2013 08:31 AM, inshu chauhan wrote:
> 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:
>          continue
>      else:
>          ix = sp[0].strip()
>          iy = sp[1].strip()
>          print ix, iy
>
>         for s in f2:
>              st = s.split(",")
>
>              if len(st)!= 11:
>                  continue
>              else:
>                  clas = st[10].strip()
>
>               print ix, iy, clas
>               print >> nf, ix, iy, clas
>
> f1.close()
> f2.close()
> nf.close()
>
>
> 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
>
>
>

The other questions are useful, but I'll make a guess based on what 
you've said so far.

You're trying to read the same file f2 multiple times, as you loop 
around the f1 file.  But you just keep the file open and try to iterate 
over it multiple times.  You either need to close and open it each time, 
or do a seek to beginning, or you'll not see any data for the second and 
later iteration.

Or better, just read file f2 into a list, and iterate over that, which 
you can do as many times as you like.  (Naturally this assumes it's not 
over a couple of hundred meg).

file2 = open(r"Z:\modules\Feature_Vectors_300_Pclass.arff")
f2 = file2.readlines()
file2.close()


-- 
DaveA



More information about the Python-list mailing list