Read a file up to a specific line in python

I have one text file. I am parsing some data using a regular expression. So open the file and read it and analyze it. But I don't want to read and parse the data after a certain line in this text file. for example

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

      

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

+3


source to share


2 answers


It's pretty straight forward, you can end the loop early with an instruction break

.

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 when entering and leaving the scope of the operator with

__enter__()

and __exit__()

will be named accordingly. For a file read, this will prevent any dangling file descriptors.

The operator break

reports that the cycle ends immediately.

+3


source


Use the parameter iter()

sentinel

:

with open('test.txt') as f:
    for line in iter(lambda: f.readline().rstrip(), 'SPECIFIC LINE'):
        print(line)

      

output:



file start here..
some data...

      

Link: https://docs.python.org/2/library/functions.html#iter

+3


source







All Articles