import re
def parse_section(start, stop, inputfile):
startpattern = re.compile(start)
stoppattern = re.compile(stop)
print_content = False
with open(inputfile, 'r') as f:
for line in f:
line = line.rstrip()
if startpattern.match(line):
print_content = True
continue
if stoppattern.match(line):
print_content = False
continue
if print_content:
print line
printing = False # Don't print until you've found a header
for line in f:
if line == " ": # Once footer is found stop printing
print line
printing = False
if printing: # Currently in between header and footer
print line
if line == "+SECTION1\n": # Once header is found start printing
print line
printing = True
要打印任意多个节,可以将此代码块放置在for循环中:
for section in ("+SECTION1\n", "+SECTION2\n", "+SECTION3\n"):
printing = False
for line in f:
if line == " ":
print line
printing = False
if printing:
print line
if line == section:
print line
printing = True
另一种方法是在脚本的某个地方添加此函数:
然后使用此命令从+SECTION1获取内容,直到
parse_section('^\+SECTION1$', '^ $', 'input.txt')
parse_section('^\+SECTION2$', '^ $', 'input.txt')
这里有一个选择:
要打印任意多个节,可以将此代码块放置在for循环中:
通常,我建议将其放在上下文管理器中:
一个干净的方法是
对于文件对象,可以使用
相关问题 更多 >
编程相关推荐