我一直在尝试让我的代码在文本文件中搜索用户输入的产品,但它只读取第一行,而不是我想要的整个文件。
这是我的代码:
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
答案 0 :(得分:0)
你突然离开了循环:
(顺便说一下,我添加了一个用于以更加pythonic的方式打开文件的statent)
order = input("Please enter the name of the product you wish to purchase\n")
with open("barcode.txt","r") as myfile:
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))
答案 1 :(得分:0)
要阅读文件,请检查:https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects
fp = open(file_name)
print fp.read() # prints all data in file name
很少有建议:
检查python的Zen,Python PEP8以及一些编程标准和样式。使代码看起来很酷。