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

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

所以我现在正在通过大学学习 python3 - 完全陌生(不是我的强项哈哈),而且我不太确定我错过了什么 - 即使在学习了我的课程内容之后

所以有问题的程序是一个基于文本的库存管理程序 部分内容是我能够在文本文件中搜索一行并在程序中打印该行

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

但是输出只是我输入的内容(如果它存在)而不是整行本身所以假设我要打印的行是 'Kit-Kat, 2003, 24.95' 并且我搜索 Kit-Kat

由于该行存在 - 输出只有

Kit-Kat

而不是整行 我哪里出错了?我离得远吗?

非常感谢,谢谢!

像这样

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

或者,您可以使用上下文管理器打开文件。这将自动处理关闭文件,这是一个例子:

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

结果:

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

设置标志,打破循环然后测试标志不是好的做法 - 它不必要地复杂。试试这个:

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