gkim
gkim

Reputation: 11

Ignore lines while reading a file in Python

The first part of my program requires me to read in a file but ignore the first few lines. The file I read in would look like:

Blah
Blah
Blah
some character(%% for example)
More Blah.

My question is, how would I read all the lines in the file but ignore the %% and every line above it?

Upvotes: 1

Views: 8511

Answers (4)

m.wasowski
m.wasowski

Reputation: 6387

You can use two argument version of iter:

with open('iter.txt') as f:
    for line in iter(f.readline, '%%\n'):
    # for line in iter(lambda: f.readline().startswith('%%'), True):
    # for line in iter(lambda: '%%' in f.readline(), True):
        pass
    for line in f:
        print line,

This iterates, until value returned by first arg (function) is not equal to the second.

Upvotes: 0

Serge Ballesta
Serge Ballesta

Reputation: 148860

You can use a flag :

with open('myfile.txt') as fd:
    skip = True
    for line in fd:
        if line.startswith("*"): skip = False
        if not skip:
            # process line

Upvotes: 0

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

with open("in.txt") as f:
    start = False
    for line in f:
        if "%%" in line:
            start = True
        if start: # if True we have found the section we want
            for line in f:
                 print(line)
   More Blah.

Upvotes: 0

tdelaney
tdelaney

Reputation: 77337

Just read and dump lines til you find the one you want. The file iterator does internal buffering, so you do it differently depending on what you want to do afterwards.

with open('somefile') as f:
    # ignore up to the first line with "%%"
    for line in f:
        if "%%" in line:
            break
    # then process the rest
    for line in f:
        do_amazing_stuff(line)

or perhaps

with open('somefile') as f:
    # ignore up to the first line with "%%"
    while True:
        line = f.readline()
        if not line or "%%" in line:
            break
    # then process the rest
    do_amazing_stuff(f.read())

Upvotes: 3

Related Questions