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?
source to share
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.
source to share