Skip to content
Advertisement

How to exact price from txt file based on the product input?

I’m fairly new to python and can’t solve this issue (I have already searched extensively)

My aim is to complete a shopping program where the user inputs the product which the program then reads the associated txt file and returns the items price.

This is my current code:

product_name_input = str(input("Please enter products name: "))

with open("products.txt") as text_file:    

    p_name  = [str(line.split(", ")[1]) for line in text_file]
    p_price = [float(line.split(", ")[2]) for line in text_file]

    while True:
        p_name == product_name_input
        print(p_price)
        break

    if product_name_input not in p_name:
        print("That product does not exist")

The current output i get if a product that is input that does exist in the file:

Please enter products name: shirt

[]

The current output i get if a product that is input that does not exist in the file:

Please enter products name: freezer

[]

That product does not exist

Any help on this is greatly appreciated!

Advertisement

Answer

In the below line, the text_file is read as an iterable and becomes empty once all the items in it are accessed

p_name  = [str(line.split(", ")[1]) for line in text_file]

A better approach would be to read all the lines into an list variable and then process them from there. Ideally construct a dictionary of name:price pairs and then query the dictionary to get the price for a product name.

product_name_input = str(input("Please enter products name: "))

with open("products.txt") as text_file:

    lines = text_file.readlines()

name_price_dict  = {str(line.split(", ")[1]):float(line.split(", ")[2]) for line in lines}

query_price = name_price_dict.get(product_name_input)

if query_price is not None:
    print(f"Price for {product_name_input} is {query_price}")
else:
    print(f"Price for {product_name_input} not found")
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement