在Python中读取文件时忽略行

时间:2014-10-28 22:37:37

标签: python readline

我程序的第一部分要求我读取文件但忽略前几行。我读过的文件看起来像是:

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

我的问题是,如何读取文件中的所有行但忽略%%及其上方的每一行?

4 个答案:

答案 0 :(得分:3)

只需读取并转储行,直到找到所需的行。文件迭代器执行内部缓冲,因此您可以根据之后要执行的操作进行不同的操作。

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)

或者

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

答案 1 :(得分:0)

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.

答案 2 :(得分:0)

您可以使用标志:

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

答案 3 :(得分:0)

您可以使用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,

迭代,直到第一个arg(函数)返回的值不等于第二个。