0
Chocolate 50
Biscuit 35
Ice cream 50
Rice 100
Chicken 250
(blank line in b/w)
Perfume Free
Soup Free
(blank line in b/w)
Discount 80

If this is the content of file, I've to iterate through, calculate the total spending and count in the discount as well and calculate the final bill amount; how to do that?

Till now I've tried this,

path=input("Enter the file name:")
listOfLines = list()
with open (path, "r") as myfile:
    for line in myfile:
        listOfLines.append(line.strip())

Here listOfLines will show the contents as list items, but i don't know what to do next?

AMC
  • 2,642
  • 7
  • 13
  • 35
  • _but i don't know what to do next?_ That's not really the kind of thing we can help with. Please see [help/on-topic], [ask]. As an aside, variable and function names should follow the `lower_case_with_underscores` style, unless there is a good reason not to do so. – AMC May 04 '20 at 04:02

1 Answers1

1

Try this. Explanation in code comment:

path=input("Enter the file name:")

# declare variables
lst_item = []
lst_price = []
discount = 0

# open file and load lines into a list
# strip() all items in the list to remove new lines and extra spaces
with open (path, "r") as myfile:
    lines = [line.strip() for line in myfile.readlines()]
# loop through the lines
for line in lines:
    # if the line is not empty and doesn't include blank line
    if line and "blank line in b/w" not in line:
        # split the line by SPACE " "
        split_line = line.split(" ")
        # join all the items of the list except the last one
        # to convert a word like Ice Cream back to one string
        # set them as the item
        item = " ".join(split_line[:-1])
        # set the price as the last item of the list
        price = split_line[-1]
        # if the price is free set it to 0
        if price == "Free":
            price = 0
        # If Discount is in the item string, set the discount variable
        if "Discount" in item:
            discount = int(price)
        # Else add item and price to lst_item and lst_price
        else:
            lst_item.append(item)
            lst_price.append(int(price))
        print (item, price)
# sum all prices in lst price
subtotal = sum(lst_price)
# minus discount
after_discount = subtotal - discount
total = after_discount

print ("Subtotal:", subtotal, "Disount:", discount, "Total:", total)

Output:

Enter the file name:in.txt
Chocolate 50
Biscuit 35
Ice cream 50
Rice 100
Chicken 250
Perfume 0
Soup 0
Discount 80
Subtotal: 485 Disount: 80 Total: 405
Thaer A
  • 2,243
  • 1
  • 10
  • 14