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

Time:06-02

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

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

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!

CodePudding user response:

Something like this

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

CodePudding user response:

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

CodePudding user response:

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