我一直试图让我的代码在文本文件中搜索用户输入的产品,但它只读取第一行,而不是我想要的整个文件。在
这是我的代码:
order=input("Please enter the name of the product you wish to purchase\n")
myfile=open("barcode.txt","r")
details=myfile.readlines() #reads the file and stores it as the variable 'details'
for line in details:
if order in line: #if the barcode is in the line it stores the line as 'productline'
productline=line
quantity=int(input("How much of the product do you wish to purchase?\n"))
itemsplit=productline.split(' ') #seperates into different words
price=float(itemsplit[1]) #the price is the second part of the line
total=(price)*(quantity) #this works out the price
print("Your total spent on this product is: " +'£'+str(total))
else:
break
您使用
break
过早退出循环:您想要使用
^{pr2}$pass
,正如@whitefret在评论中所说:或者您可以完全忽略
else
:你的代码会在1行被检查后中断。在
你有
所以如果订单不在第一行,它就退出循环。在
你很可能在找类似的东西
^{pr2}$尽管在这种情况下,不需要
else: continue
分支,因为如果找不到顺序,您不打算执行任何操作。在顺便说一句,文件自然地支持迭代,所以不需要执行以下操作
完成后不要忘记关闭文件,使用
myfile.close()
,或者使用类似的上下文管理器你正在打破循环:
(顺便说一句,我添加了一个with语句,用于以一种更python的方式打开文件)
相关问题 更多 >
编程相关推荐