In: Computer Science
Write a program that reads such a file and displays the total amount for each service category. Use the following data for your text file:5 pts
Bob;Dinner;10.00;January 1, 2013
Tom;Dinner;14.00;January 2, 2013
Anne;Lodging;125.00;January 3, 2013
Jerry;Lodging;125.00;January 4, 2013
The output should be:
Dinner: 24.00
Lodging: 250.00
Python, keep it simple, thank you
Please find the answer below.
Please do comments in case of any issue. Also, don't forget to rate
the question. Thank You So Much.
code.py
def main():
#name of the file
#fileName = input("Enter file name : ")
fileName="sales.txt"
#try block to avoid any run time exception
try:
#store all sale service wise
allSale={}
#open file with
with open(fileName) as f:
#read all lines from the file
content = f.readlines()
#strip all space from the file
content = [x.strip() for x in content]
#for each row in content
for record in content :
#split row by comma
records= record.split(";");
#now service will be at index 1 and bill amount will be at index
2
if(records[1] in allSale):
allSale[records[1]]=allSale[records[1]]+float(records[2])
else:
allSale[records[1]]=float(records[2])
#for each key in sale
for key in allSale:
print(key,":",allSale[key])
except:
print("Error in opening file")
return []
main()