2014-10-28 26 views
1

我的程序的第一部分需要我读入文件,但忽略前几行。我读的文件看起来像:在Python中阅读文件时忽略行

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

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

回答

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

你可以使用一个标志:

with open('myfile.txt') as fd: 
    skip = True 
    for line in fd: 
     if line.startswith("*"): skip = False 
     if not skip: 
      # process line 
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(函数)返回的值不等于第二个。