ignore specific data

Mike Meyer mwm at mired.org
Mon Nov 21 20:47:52 CET 2005

pkilambi at gmail.com writes:
> Hi I need help. What I want to do is If I read a file with some text
> content...
> I would like to ignore a block of lines and consider the rest..
> so if the block starts with
> "start of block............."
> fjesdgsdhfgdlgjklfjdgkd
> jhcsdfskdlgjkljgkfdjkgj
> "end of block"
> I want to ignore this while processing the file .This block could
> appear anywhere in the file.It could at the start or end or even middle
> of file content.

The best way depends on how you're going to use the data. For
instance, if you're going to be processing line at a time, you might
consider writing an interator:

# Untested code:

def filter(rawfile):
    for line in rawfile:
        if line == "start of block......":
        yield line
    for line in rawfile:
        if line == "end of block":
    for line in rawfile:
        yield line

Then you use it like:

myfile = open(...)
for line in filter(myfile):

This is a straightforward translation of your description, and avoids
loading the entire file into memory at once. You might be able to cons
up something more efficient from itertools.

Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.

More information about the Python-list mailing list