在txt fi中打印到点之间

2024-04-25 21:42:26 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我想写一个脚本,通过一个文件进行解析,在两点之间打印一个特定的部分。我想这样做:

+SECTION1
stufff
stufffff
more stufff
--

我想打印从+SECTION1到--。我还计划有第二节,第三节等等。有没有一种简单的方法可以在python中实现这一点?你知道吗


Tags: 文件方法脚本more计划section1stufffffstufff
3条回答

另一种方法是在脚本的某个地方添加此函数:

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')
  • 以此类推:)

这里有一个选择:

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:

一个干净的方法是

对于文件对象,可以使用

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

相关问题 更多 >