你怎么让python读取整个文本文件,而不仅仅是一行?

时间:2016-04-06 12:44:16

标签: python text-files

我一直在尝试让我的代码在文本文件中搜索用户输入的产品,但它只读取第一行,而不是我想要的整个文件。

这是我的代码:

 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

2 个答案:

答案 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

很少有建议:

  • 立即获取所有输入。 #nt like quantity = int(输入("多少t"
  • 一次读取所有数据。
  • 获得所有变量后,现在开始处理逻辑。
  • 你不需要做" productline = line"
  • 如果您不需要'否则',则不要使用它。

检查python的Zen,Python PEP8以及一些编程标准和样式。使代码看起来很酷。