file handling and lists in python – We’re going to create some summary data for a hardware store by reading their file of sales and creating some
- The file name is inventory.txt. Download the file and save it in the same directory as your .py files will be.
- Open the file inventory.txt and look at it. You’ll see that each line has 3 pieces of information. The first
is the department name. We only have a Lighting, a Plumbing and a Garden department at our little
store. Be careful to not make any changes to this file. If you happen to make a change, feel free to
download a “clean” version of the file and start over
Your job is to write a program that calculates the total sales for the hardware store as well as the total sales
for each department.(file handling and lists in python)
Your final output should look like this (with the correct numbers, though). Notice the line spacing and
formatting of the values.
Sales by Department:
Total Sales: $10232.79
- Each line in the file must be read as a string and then split into a list.
- Based on the department name in the line that was just read, add the value of the sales to the total
sales for that department. Remember, we read the line as a string, converted it to a list of strings – but
we can only add numbers. You will be ignoring the second data value in each line…..for now.
- At the end, print the total sales for the entire store.
Assumptions that you may make:
- The file exists and contains at least one line.
- There are no lines which have any department other than those 3 departments.
- All data is “valid” (i.e. the 3rd value in each line is a number, the 1st value is a valid department)
file_name = "inventory.txt"
my_file = open(file_name,"r")
lines = my_file.readlines()
total_sales = 0.0
Plumbing = 0
Lighting = 0
Garden = 0
total = 0
for line in lines:
data = line.split(",")
department = data
sales = float(data)
if department == "Plumbing":
Plumbing += sales
if department == "Lighting":
Lighting += sales
if department == "Garden":
Garden += sales
total += sales
print("Sales by Department:\n")
print("Garden : $",round(Garden,2))
print("\nTotal Sales: $",round(total,2))
keep visiting : shaadcoding