Reading data from 2 different files and writing to a single file
Chris Angelico
rosuav at gmail.com
Mon Jan 28 09:32:30 EST 2013
On Tue, Jan 29, 2013 at 1:24 AM, inshu chauhan <insideshoes at gmail.com> wrote:
>> In that case, Dave's suggestion to read into a list and iterate over
>> the list is to be strongly considered. But I'm not entirely sure what
>> your goal is here. Are you trying to make the Cartesian product of the
>> two files, where you have one line in the output for each possible
>> pair of matching lines? That is, for each line in the first file, you
>> make a line in the output for each line in the second? That's what
>> your code will currently do.
>
> No , I dont want that , actually both files have equal no of lines, I want
> to read the first line of f1 , take 2 datas from it, nd then read first line
> of f2, take data from it,
> then print them to the same first line of new file i.e nf.
Okay, so you want an algorithm something like this:
for l1 in f1:
# make sure you have the right sort of line, and 'continue' if not
for l2 in f2:
# same again, 'continue' if not right
print >> nf # whatever you need to output
break
The 'break' in the second loop will mean that it never consumes more
than one valid line. You still need to deal with the possibilities of
one file being shorter than the other, of the lines mismatching, etc,
but at least you don't get a failed Cartesian product.
ChrisA
More information about the Python-list
mailing list