[Tutor] Multiple file open
Sander Sweers
sander.sweers at gmail.com
Wed Aug 18 23:40:57 CEST 2010
On 18 August 2010 17:14, nitin chandra <nitinchandra1 at gmail.com> wrote:
> I am on Python 2.6
>
<snipped a whole lot of text>
> Please guide with the syntax.
All beginners tutorials on the web teach the syntax of python.. I am
unsure what your questions is.
> below is the existing program with Formula A (Mean). Formula B will be
> Extrapolation,
> also I have not been able to do justice to 'except IOError:' part.The
It has many errors which need fixing but..
> program ends with an error.
And if you get an error always make sure you provide it to this list.
People on this list can not read minds ;-).
> ********************************
> 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')
What happens when you enter a wrong filename? It will raise IOError
the moment you use open(). Below is 1 example of what you might want
tot do.
file11 = raw_input('Enter PR1 File name :')
try:
fp1 = open(ffile11, 'r')
except IOError:
sys.exit('Could not open file: %s' % file11)
> while True:
> try:
> line1A = fp1.readline()
You can read and split the line in 1 go.
line1 = fp1.readline().split(",")
> line1B = fp2.readline()
> line1 = line1A.split(",")
You can now remove the above, see earlier comment.
> 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]
Above you create a list "line1 = fp1.readline().split(",")". Lists are
mutable so you can add, remove and insert new items. You can also
access the items in the list by index. You can even add 2 lists to
make a new list, eg: .
>>> [1,2,3,4,5] + [6,7,8,9,0]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
Now try and apply this to all your col<num> variables.
> # calculation of PR2 as per formula
> #(A+B)/2 , ie. Mean of the two values
> col14 = ( (float(col2)) + (float(col8)) / 2)
You can write this as:
col14 = (float(line1[1])) + (float(line2[1])) / 2)
And avoid creating all these col variables. But what would happen if
col2/line1[1] has a value of "I am not a number"? Do note the comment
below on the actual calculation.
> col15 = ( (float(col3)) + (float(col9)) / 2)
<snipped some more>
> col19 = ( (float(col7)) + (float(col13)) / 2)
Your "mean" calculation is wrong (hint, division has precedence over adding).
Greets
Sander
More information about the Tutor
mailing list