hppylttletrees hppylttletrees -4 years ago 130
Python Question

Reading Data from a File in Python with Exceptions

I have to write a program that will read data from a file, convert it to an integer and total the amount. So far here is what i have. The numbers from the data file "numdata.txt" are: 78,93,85,100,81,76,94,77.

def main():
total = 0

try:
NumberFile = open('numdata.txt', 'r')

for line in NumberFile:
amount = float(line)
total += amount
print(format(total, ',.2f'))

except IOError:
print('An error occurred trying to read the file.')

except ValueError:
print('Non-numeric data found in the file.')

except:
print('An error has occurred.')

finally:
NumberFile.close()


main()


When i run the program the first number (78) gets displayed and then one of the exception error messages comes up, the weird thing is that it's different sometimes. If someone could help point me in the right direction I'd appreciate it. I'm still very new to this so please bear with me.

I tried and tried but could not get the loop to work correctly so i ended up going this route:

def main ():
infile = open('numdata.txt', 'r')
num1 = int(infile.readline())
num2 = int(infile.readline())
num3 = int(infile.readline())
num4 = int(infile.readline())
num5 = int(infile.readline())
num6 = int(infile.readline())
num7 = int(infile.readline())
num8 = int(infile.readline())
infile.close()
total = num1+num2+num3+num4+num5+num6+num7+num8
average = total/8
print('the total: ', total)
print('the average: ', average)


main()

It's not pretty but it works i guess lol

Answer Source
total = 0    

try:
    NumberFile = open('numdata.txt', 'r')

    for line in NumberFile:
        amount = float(line)
        total += amount
        print(format(total, ',.2f'))
except IOError:
    print('An error occurred trying to read the file.')
except ValueError:
    print('Non-numeric data found in the file.')
except:
    print('An error has occurred.')
finally:
    NumberFile.close()

The exception occurs because you're closing the file immediately after the first iteration, leaving you unable to iterate over the rest of it.

Moving NumberFile.close() to a finally clause ensures the file is closed no matter what goes wrong. However, a much better way to read / write files in Python is to use the with keyword, which is a built-in method of ensuring the same thing.

total = 0

with open('numdata.txt', 'r') as f:
  for line in f:
      try:
        total += float(line)
      except ValueError:
        print('Non-numeric data found in the file.')
        continue
      print('{:.2f}'.format(total, ',.2f'))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download