簡體   English   中英

在Python中讀取文件時忽略行

[英]Ignore lines while reading a file in Python

我的程序的第一部分要求我讀取文件但忽略前幾行。 我讀過的文件看起來像:

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

我的問題是,如何讀取文件中的所有行但忽略%%及其上面的每一行?

只需讀取並轉儲線,直到找到所需的線。 文件迭代器執行內部緩沖,因此您可以根據之后要執行的操作進行不同的操作。

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

你可以使用一個標志:

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

你可以使用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(函數)返回的值不等於第二個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM