Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read file until specific line in python

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?

like image 579
SAM Avatar asked Nov 25 '14 19:11

SAM


People also ask

How do I read a specific part of a file in Python?

Method 1: fileobject.readlines() A file object can be created in Python and then readlines() method can be invoked on this object to read lines into a stream. This method is preferred when a single line or a range of lines from a file needs to be accessed simultaneously.

How do you return to a specific line in Python?

Python does not allow you to go back to a specific line number, and even if it did, you should not take advantage of that capability because it results in unmaintainable programs. Instead, learn how to use functions and structure your code so that functions make sense.


2 Answers

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.

like image 52
Mike McMahon Avatar answered Oct 21 '22 22:10

Mike McMahon


Use iter()'s sentinel parameter:

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

output:

file start here..
some data...

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

like image 41
Raymond Avatar answered Oct 21 '22 23:10

Raymond