2016-03-24 1 views
1

私はいくつかの項目について、製品コードを入力すると、プログラムはテキストファイルにコードをルックアップするために、画面上の項目のコード/名/価格を提示し、ユーザに依頼する私のプログラムを取得しようとしています。最初のコードを見つけますのPython 3シリアル探索は一つだけ結果を見つけましたか?

私のコードが入力されますが、入力された後続のコードが見つかりましたことはありません - プログラムは今まで、ユーザーが探していることを最初の項目が表示されます。

はなぜ私のコードは、複数の項目を検索し、表示されないのでしょうか?

私は3行でテキストファイルがあります:コードで

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...
  2. ループfor x in...内部プロセスを置いてもよいです辞書for x ...ループの前に

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

    、および

    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!") 
関連する問題