我試圖讓我的程序要求用戶輸入某些項目的產品代碼,然後讓程序在文本文件中查找代碼並在屏幕上顯示代碼/名稱/價格。通過文本文件的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!")
你需要在每個循環結束時使用'f.seek(0)'來重置指針,更好的選擇是創建一組item_list並用於在文件上循環一次 –