codersick07
codersick07

Reputation: 25

How to iterate through contents of the text file in the directory and make specific calculations as well in python?

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?

Upvotes: 0

Views: 59

Answers (1)

Thaer A
Thaer A

Reputation: 2323

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

Upvotes: 1

Related Questions