I am trying to let the user search an external file for 2 things after they tell me one of the things.. There are 3 different products and prices in the txt file in the form of:
apple
1.99
orange
9.99
coconut
1.59

however, this only shows the price of the apple, not the other two.. what's wrong?

def search():

    keepgoing = True
    foundproduct = False
        
    while keepgoing == True:
            
        searchterm = input("What are you looking for? (type 'end' to quit)")
        if searchterm == 'end':
            keepgoing == False
            
        file_object = open('herp.txt', 'r')

        product = file_object.readline()
        price   = file_object.readline()
            
        product = product.rstrip("\n")
        price   = price.rstrip("\n")
        
        
        if product == '':
            keepgoing = False
        else:
            
            if searchterm == product:
                print("Product: ", product, "| Price: ", price)
                foundproduct == True
            else:
                print("Sorry, can't find it!")
    file_object.close() 

search()

Recommended Answers

All 3 Replies

You should have for loop over the file's lines instead of single if, alternating between product and price. You could also read all lines in one go and do every second slice [::2] to separate the products and prices. The lower method of strings could be also usefull to fix user input.

Some code that should help,it is close to what pyTony suggests.
Making a dictionary will be suited for this.

with open('fruit.txt') as f:
    l = [i.strip() for i in f]
    my_dict = dict(zip(l[0::2], l[1::2]))

Test in IDLE.

>>> my_dict
{'apple': '1.99', 'coconut': '1.59', 'orange': '9.99'}
>>> search = 'apple'
>>> if search in my_dict:
...     print my_dict[search]
...     
1.99
>>>

You open the file every pass through the loop, and only read one record. Read the file once before the loop and store it (like the list of lists below), then access the stored values.

file_object = open('herp.txt', 'r')
data_as_list = file_object.readlines()
file_object.close()

product_list_of_lists = []
##  process 2 records at a time
for ctr in range(0, len(data_as_list), 2):
    product = data_as_list[ctr].strip()
    price = data_as_list[ctr+1].strip()
    product_list_of_lists.append([product, price])
for product, price in product_list_of_lists:
    print product, price
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.