Reading data from 2 different files and writing to a single file
Dave Angel
d at davea.name
Mon Jan 28 09:37:51 EST 2013
On 01/28/2013 09:12 AM, inshu chauhan wrote:
> Yes Chris, I understand, My Original code was
>
> for l in f1:
> sp = l.split(",")
>
> if len(sp)!= 12:
> continue
> else:
> ix = sp[0].strip()
> iy = sp[1].strip()
>
>
> 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()
>
> where f1 contains something like :
>
> 297, 404, , ....
> 298, 404, , ......
> 299, 404, .....
> ..... ......
> 295, 452, ....
>
> and f2 contains something like :
>
> .... 7
> ..... 2
> ....2
> .....7
>
> and what I want to be written in the new file i.e. nf is something like:
>
> 297 404 7
> 297 404 7
> 297 404 7
> 297 404 7
> 297 404 7
> 297 404 7
> 297 404 7
> 297 404 7
> 297 404 7
> 297 404 7
> 297 404 7
> 297 404 7
> 297 404 7
> 297 404 7
> 297 404 2
> 297 404 2
> 297 404 2
> 297 404 2
> 297 404 2
>
> which m getting but partially correct because only last value is changing
> not the first two... which should not happen.. In every loop all the three
> values should change..
>
>
Your current logic tries to scan through the first file, and for each
line that has 12 elements, scans through the entire second file. It
fails to actually do it, because you never do a seek on the second file.
Now it appears your requirement is entirely different. I believe you
have two text files each having the same number of lines. You want to
loop through the pair of lines (once from each file, doing some kind of
processing and printing). If that's the case, your nested loop is the
wrong thing, and you can forget my caveat about nesting file reads.
What you want is the zip() function
for l,s in zip(f1, f2):
#you now have one line from each file,
# which you can then validate and process
Note, this assumes that when a line is "bad" from either file, you're
going to also ignore the corresponding line from the other. If you have
to accommodate variable misses in the lining up, then your work is
*much* harder.
--
DaveA
More information about the Python-list
mailing list