如何让python读取整个文本文件,而不仅仅是一行?

2024-09-24 22:20:23 发布

您现在位置:Python中文网/ 问答频道 /正文

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

这是我的代码:

 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

Tags: ofthe代码inyouinputisline
3条回答

您使用break过早退出循环:

for line in details:
        if order in line:
            # do stuff
        else:
            break  #<-- this is exiting the loop

您想要使用pass,正如@whitefret在评论中所说:

^{pr2}$

或者您可以完全忽略else

for line in details:
        if order in line:
            # do stuff

你的代码会在1行被检查后中断。在

你有

for line in details:
    if order in line:
        # Does stuff
    else:
        break
        # This breaks out of the `for line in details` loop.

所以如果订单不在第一行,它就退出循环。在

你很可能在找类似的东西

^{pr2}$

尽管在这种情况下,不需要else: continue分支,因为如果找不到顺序,您不打算执行任何操作。在

顺便说一句,文件自然地支持迭代,所以不需要执行以下操作

myfile = open("barcode.txt", "r")
details = myfile.readlines()
# this line ^ can be removed, and you can just iterate over the file object itself 
for line in myfile:
    # do stuff

完成后不要忘记关闭文件,使用myfile.close(),或者使用类似的上下文管理器

with open("barcode.txt", "r") as myfile:
    for line in myfile:
        # Do stuff
# Once you go out of the `with` context, the file is closed for you

你正在打破循环:
(顺便说一句,我添加了一个with语句,用于以一种更python的方式打开文件)

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))

相关问题 更多 >