[Tutor] Multiple file open

nitin chandra nitinchandra1 at gmail.com
Wed Aug 18 17:14:36 CEST 2010

Hi All,

@ Alan - Thank you. Your suggestion worked. ( read 2 input file and 1
output file).

I am on Python 2.6

I need to process two sets of 96 files and prepare equal no. of sets
of 96 files. The first set of 96 files have a formula A and second set
of 96 files have formula B. Formula A is derived as follows - from 2
input files in 2 different paths, read 4 columns each, (add, sub, div,
etc) and write it to a One output file in 3rd different path.(This
part is done, but will require me to run it 96 times, you can imagine
my plight).

Change the formula and make another PY script and then run it ..... 96
times ..... again ...

So I was thinking like this

create a CSV file with a list of files for formula A and create a 2nd
CSV file with a list of files for formula B.
as follows :

column 1 will have full path of FIRST INPUT file to pass to the
existing Program.
column 2 will have full path of SECOND INPUT file to pass to the
existing Program.
column 3 will have full path of THIRD OUTPUT file to pass to the
existing Program.

a switch statement to choose between Formula A or Formula B or Exit.

Please guide with the syntax.

below is the existing program with Formula A (Mean). Formula B will be
also I have not been able to do justice to 'except IOError:' part.The
program ends with an error.

Thanks In Advance.


import sys,os, fileinput

file11 = raw_input('Enter PR1 File name :')
fp1 = open(file11,'r')

file12 = raw_input('Enter PR3 File Name :')
fp2 = open(file12,'r')

file3 = raw_input('Enter PR2 / PR4 OUTPUT File Name :')
fp3 = open(file3,'w')

while True:
       line1A = fp1.readline()
       line1B = fp2.readline()
       line1 = line1A.split(",")
       col1 = line1[0]
       col2 = line1[1]
       col3 = line1[2]
       col4 = line1[3]
       col5 = line1[20]
       col6 = line1[21]
       col7 = line1[22]
       line2 = line1B.split(",")
       col8 = line2[1]
       col9 = line2[2]
       col10 = line2[3]
       col11 = line2[20]
       col12 = line2[21]
       col13 = line2[22]
       # calculation of PR2 as per formula
       #(A+B)/2 , ie. Mean of the two values
       col14 = ( (float(col2)) + (float(col8)) / 2)
       col15 = ( (float(col3)) + (float(col9)) / 2)
       col16 = ( (float(col4)) + (float(col10)) / 2)
       col17 = ( (float(col5)) + (float(col11)) / 2)
       col18 = ( (float(col6)) + (float(col12)) / 2)
       col19 = ( (float(col7)) + (float(col13)) / 2)

       print col1,col14,col15,col16,col17,col18,col19
       str3 = '%s,%s,%s,%s,%s,%s,%s\n' %

   except IOError:
         print 'Error in One of the Input Files'


More information about the Tutor mailing list