2016-03-24 23 views
1

我試圖讓我的程序要求用戶輸入某些項目的產品代碼,然後讓程序在文本文件中查找代碼並在屏幕上顯示代碼/名稱/價格。通過文本文件的Python 3串行搜索只能找到一個結果 - 爲什麼我的搜索循環無法正確找到後續項目?

我的代碼會找到第一個輸入的代碼,但是從未找到任何後續輸入的代碼 - 程序只顯示用戶正在搜索的第一個項目。

爲什麼我的代碼無法找到並顯示多個項目?

我有三條線的TXT文件:

12312356 product1 1.50 
76576543 product2 6.20 
98765423 product3 2.20 

和Python程序與代碼:

 item_list = [] 
     item_quantity = [] 
     item_order = True 
     while item_order == True: 
      item_code = input("What is the code of the product you require? ") 
      item_list.append(item_code) 
      quantity = int(input("What quantity: ")) 
      item_quantity.append(quantity) 
      repeat = input("Would you like to enter another item? (Y/N): ") 
      if repeat == "N": 
       item_order = False 

     with open("stockfile.txt", "r") as f: 
      for x in range(len(item_list)): 
       product_found = False 
       for a_line in f: 
        if item_list[x] in a_line: 
         print(a_line, end="") 
         product_found = True 
       if product_found == False: 
        print("Product with code", item_list[x], "not found!") 
+2

你需要在每個循環結束時使用'f.seek(0)'來重置指針,更好的選擇是創建一組item_list並用於在文件上循環一次 –

回答

1

您打開一個文件,然後對每一個要求你閱讀所有的文件,但在處理完第一個請求之後,您將處於文件結尾,因此當您再次對文件進行迭代以處理以下用戶請求時,for a_line in f:的正文從不處理。

您可以

  1. with open...for x in...
  2. 過程中的文件自動,例如使用字典

    d = {code:[name,price] for code, name, price in [l.split() for l in f]} 
    

    for x ...循環之前,並在身體剛剛測試

    if something in d: 
    
1

我周圍的其他方法寫出來。

with open("stockfile.txt", "r") as f: 
      for a_line in f: 
       # to get the product name 
       product = a_line.split(" ")[1] 
       if product in item_list: 
        item_list.remove(product) 

      if len(item_list)>0: 
       for product in item_list: 
        print("Product with code", product, "not found!") 
相關問題