在txt文件中的点之间打印

时间:2014-01-22 03:26:48

标签: python scripting

所以我想写一个解析文件的脚本打印两点之间的特定部分。我想做这样的事情:

+SECTION1
stufff
stufffff
more stufff
--

我想打印从+ SECTION1到 - 的所有内容。我还计划有第2,3节等等。有没有一种简单的方法来在python中实现这一目标?

3 个答案:

答案 0 :(得分:1)

这是一个选项:

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  

正常情况下,我建议将其放在上下文管理器中:

with open('file.txt', 'w') as f:

答案 1 :(得分:1)

另一种方法是在脚本的某处添加此功能:

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

然后使用此命令从 + SECTION1 获取内容,直到 -

  • parse_section('^\+SECTION1$', '^--$', 'input.txt')
  • 并且对于 + SECTION2 ,您可以:parse_section('^\+SECTION2$', '^--$', 'input.txt')
  • 依此类推:))

答案 2 :(得分:0)

干净的方法可能是

对于您可以使用的文件对象

    f = open('workfile', 'r')
    for line in f:
        if line == '--':
            print "next section"
        else:
            print "the same section`