0

Mini project to practice file handling and lists in python

ractice file handling and lists in python

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
departmental totals.

  1. The file name is inventory.txt. Download the file and save it in the same directory as your .py files will be.
  2. 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:
Plumbing: $3568.24
Lighting: $241.34
Garden: $6423.21
Total Sales: $10232.79

Requirements:

  1. Each line in the file must be read as a string and then split into a list.
  2. 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.
  3. At the end, print the total sales for the entire store.

Assumptions that you may make:

  1. The file exists and contains at least one line.
  2. There are no lines which have any department other than those 3 departments.
  3. All data is “valid” (i.e. the 3rd value in each line is a number, the 1st value is a valid department)

CODE

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[0]

sales = float(data[2])

if department == "Plumbing":
Plumbing += sales

if department == "Lighting":
Lighting += sales
if department == "Garden":
Garden += sales

total += sales




print("Sales by Department:\n")

print("Plumbing: $",round(Plumbing,2))
print("Lighting: $",round(Lighting,2))
print("Garden : $",round(Garden,2))



print("\nTotal Sales: $",round(total,2))

keep visiting : shaadcoding

shaad

Leave a Reply

Your email address will not be published. Required fields are marked *