Python File Reading And Printing, With Exceptions And Terminations
Hello I am a very new programmer who is self teaching Python. I have encountered a very interesting problem and need some help in creating a program for it. It goes like this A hot
Solution 1:
Here's a basic sketch. This is untested so likely contains typos, logic errors and such. Also, it doesn't check all of the error conditions you mentioned. However, it should be enough to get your started. The main trick is to just throw an exception where you encounter an error, and catch it where you can deal with it. That immediately stops processing the file as you wanted. The other trick is to keep a dictionary mapping category to total so you can keep a running total by category.
def main():
# Req 1.1: ask for a filename
file_name = input("Input file name: ")
try:
# To keep things simple we do all the file processing
# in a separate function. That lets us handle
# any error in the file processing with a single
# except block
amount_by_category = process_file(file_name)
# Req 6: display the categories - python will
# display the contents of a data structure when we print() it
print('Totals: ', amount_by_category)
except Exception, e:
# Reqs 1-3: display errors
print('Error processing file:', e)
def process_file(file_name):
# Req 1.2: open the file
infile = open(file_name, 'r')
# Req 4.1: somewhere to remember the categories
amount_by_catgeory = {}
# Reqs 2-4: we are dealing with a many line file
# Req 5: when we reach the end, python closes the file for us automatically
for line in infile:
# Req 2.1: each line should have 4 values separated by ;
fields = line.split(';')
# Req 2.2: does this line have 4 values?
if len(fields) != 4:
raise Exception('Expected 4 fields but found %s' % len(fields))
# Req 3: is the third value a number?
value = float(fields[2])
# Req 4.2: what category does this line belong to?
category = fields[1]
# Req 4.3.1: have we seen this category before?
if not category in amount_by_category:
# Req 4.3.2: accumulations start from 0?
amount_by_category[category] = 0.0f
# Req 4.4: increase the cumulative amount for the category
amount_by_category[category] += value
return amount_by_category
Post a Comment for "Python File Reading And Printing, With Exceptions And Terminations"