alank_ok
alank_ok

Reputation: 13

I want to read back a line from a specific line/string in python

this is the code that has me really confused:

if search in open('test.txt').read():
    print("product is found")

i am trying to re-read a line fro my text file using the .read() function however i do not know how this would work from searching a single string. EG: if search is 12345 i want to find this in the text file and then output it on the shell. I have tried numerous different ways but cannot get it to work. This is for my work experience and would help me a lot.

Upvotes: 0

Views: 238

Answers (1)

Leonid Mednikov
Leonid Mednikov

Reputation: 973

If I understood you right, you want to get the line which matches the search. If so, you just need to read file line by line which can be done like this

for line in open('test.txt'):
    if search in line:
        print("Product is found on line", line.strip())

Upvotes: 1

Related Questions