简体   繁体   English

在Python中读取文件时忽略行

[英]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 : 你可以使用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. 这将迭代,直到第一个arg(函数)返回的值不等于第二个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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