简体   繁体   English

如何在python3中从txt文件中搜索和打印一行?

[英]How to search and print a line from txt file in python3?

So I'm learning python3 at the moment through university - entirely new to it (not really a strong point of mine haha) , and i'm not quite sure what i'm missing - even after going through my course content所以我目前正在通过大学学习 python3 - 对它来说是全新的(不是我的强项哈哈) ,而且我不太确定我错过了什么 - 即使在完成我的课程内容之后

So the program in question is a text based Stock Management program and part of the brief is that i be able to search for a line in the text file and print the line on the program所以有问题的程序是一个基于文本的库存管理程序,部分简介是我能够在文本文件中搜索一行并在程序上打印该行

def lookupstock():
StockFile = open('file.txt', 'r')
flag = 0
index = 0
search = str(input("Please enter in the Item: "))

for line in StockFile:
    index += 1

    if search in line:
        flag = 1
        break

if flag == 0:
    print(search, "Not Found")
else:
    print(search)
    StockFile.close()

However the output is only what i have typed in if it exists rather than the whole line itself so lets say the line i want to print is 'Kit-Kat, 2003, 24.95' and i search for Kit-Kat但是,输出只是我输入的内容(如果它存在)而不是整行本身,所以假设我要打印的行是“Kit-Kat, 2003, 24.95”,我搜索 Kit-Kat

Since the line exists - the output is only由于该行存在-输出仅

Kit-Kat

Rather than the whole line Where have I gone wrong?而不是整行 我哪里出错了? Was I far off?我离得很远吗?

Greatly appreciated, thank you!非常感谢,谢谢!

Something like this像这样的东西

if flag == 0:
    print(search, "Not Found")
else:
    print(search, 'find in line N° ', index , ' line:',line )
    StockFile.close()

Alternatively you could open your file using a context manager.或者,您可以使用上下文管理器打开文件。 This will automatically handle closing the file, here's an example:这将自动处理关闭文件,这是一个示例:

def lookupstock():
    flag = False
    with open('file.txt', 'r') as StockFile:
        search = str(input("Please enter in the Item: "))
        for index, line in enumerate(StockFile):
            if search in line:
                print(line, f"Found at line {index}")
                flag = True
    if not flag:
        print(search, "Not Found")

lookupstock()

Results:结果:

Please enter in the Item: test
test Not Found
Please enter in the Item: hello
hello Found at line 0

Setting flags, breaking the loop then testing the flag is not good practice - it's unnecessarily complex.设置标志,打破循环然后测试标志不是好的做法 - 它不必要地复杂。 Try this instead:试试这个:

def LookupStock():
    search = input('Enter search item: ')
    with open('file.txt') as StockFile:
        for line in StockFile:
            if search in line:
                print(line)
                break
        else:
            print(search, ' not found')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM