Read file until specific line in python

SAM picture SAM · Nov 25, 2014 · Viewed 13.7k times · Source

I have one text file. I am parsing some data using regex. So open the file and read it and the parse it. But I don't want to read and parse data after some specific line in that text file. For example

file start here..
some data...
SPECIFIC LINE
some data....

Now I don't want to read file after SPECIFIC LINE... Is there any way to stop reading when that line reaches?

Answer

Mike McMahon picture Mike McMahon · Nov 25, 2014

This is pretty straight forward, you can terminate a loop early with a break statement.

filename = 'somefile.txt'

with open(filename, 'r') as input:
   for line in input:
       if 'indicator' in line:
            break

Using with creates a compound statement that ensures that upon entering and leaving the scope of the with statement __enter__() and __exit__() will be called respectively. For the purpose of file reading this will prevent any dangling filehandles.

The break statement tells the loop to terminate immediately.