在两个分隔符之间打印文本?

时间:2014-12-29 13:35:39

标签: python python-2.7

我有配置文件:

$ cat ../secure/test.property
#<TITLE>Connection setting
#MAIN DEV
jdbc.main.url=
jdbc.main.username=
jdbc.main.password=

#<TITLE>Mail settings
mail.smtp.host=127.0.0.1
mail.smtp.port=25
mail.smtp.on=false

email.subject.prefix=[DEV]

#<TITLE>Batch size for package processing
exposureImportService.batchSize=10
exposureImportService.waitTimeInSecs=10

ImportService.batchSize=400
ImportService.waitTimeInSecs=10

#<TITLE>Other settings
usePrecalculatedAggregation=true

###################### Datasource wrappers, which allow to log additional information
bean.datasource.query_log_wrapper=mainDataSourceWrapper
bean.gpc_datasource.query_log_wrapper=gpcDataSourceWrapper

time.to.keep.domain=7*12
time.to.keep.uncompress=1

#oracle max batch size
dao.batch.size.max=30

和函数,返回行“#<TITLE>Other settings”(例如),选择“config section”。

接下来,需要打印所选“部分”和下一行startwith #<TITLE>之间的所有行。

如何实现?

P.S。

def select_section(property_file):

    while True:

        with open(os.path.join(CONF_DIR, property_file), 'r+') as file:

            text = file.readlines()
            list = []

            print()

            for i in text:
                if '<TITLE>' in i:
                    line = i.lstrip('#<TITLE>').rstrip('\n')
                    list.append(line)
                    print((list.index(line)), line)

            res_section = int(raw_input('\nPlease, select section to edit: '))
            print('You selected: %s' % list[res_section])

            if answer('Is it OK? '):
                return(list[res_section])
                break

它的工作方式如下:

...
0 Connection setting
1 Mail settings
2 Batch size for package processing
3 Other settings

Please, select section to edit:
...

预期输出,如果选择Connection setting

...
0 jdbc.main.url
1 jdbc.main.username
2 jdbc.main.password

Please, select line to edit:
...

2 个答案:

答案 0 :(得分:1)

这是一个快速解决方案:

def get_section(section):
    results = ''
    with open('../secure/test.property') as f:
        lines = [l.strip() for l in f.readlines()]

    indices = [i for i in range(len(lines)) if lines[i].startswith('#<TITLE>')]

    for i in xrange(len(indices)):
        if lines[indices[i]] == '#<TITLE>' + section:
            for j in xrange(indices[i], indices[i+1] if i < len(indices)-1 else len(lines) - 1):
                results += lines[j] + '\n'
            break

    return results

您可以像以下一样使用它:

print get_section('Connection setting')

不是很优雅,但它有效!

答案 1 :(得分:1)

如果我正确理解了这个问题,这里有一个解决方案,它会在读取文件时组合所请求的部分:

def get_section(section):
    marker_line = '#<TITLE>{}'.format(section)
    in_section = False
    section_lines = []
    with open('test.property') as f:
        while True:
            line = f.readline()
            if not line:
                break
            line = line.rstrip()
            if line == marker_line:
                in_section = True
            elif in_section and line.startswith('#<TITLE>'):
                break

            if in_section:
                if not line or line.startswith('#'):
                    continue
                section_lines.append(line)
    return '\n'.join(['{} {}'.format(i, line)
                            for i, line in enumerate(section_lines)])

print get_section('Connection setting')

输出:

0 jdbc.main.url=
1 jdbc.main.username=
2 jdbc.main.password=

也许这会让你开始。