简体   繁体   中英

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?

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())
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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM