Finding a spesific string and getting its line in PYTHON 3.X

46 views Asked by At

Lets say I am trying to find a spesific string in a txt file in python and I want to get that line how do I do it?

1

There are 1 answers

5
Joe Iddon On BEST ANSWER

Say your file is called file.txt, you can use next() on a generator expression which yields the indexes of lines in the file containing your_string. To be able to work with the indexes and the contents, we can use enumerate():

next(i for i, l in enumerate(open('file.txt').readlines()) if 'your_string' in l)