键和多行python值

时间:2015-11-16 19:37:15

标签: python string

我正在尝试阅读文本文件或在具有以下结构的文件上使用ConfigParser

        Index1 = '''You have been redirected to this page for one of the following 

        reasons:

        Either cookies are not enabled on your browser
        or
        Your network configuration is causing cookies to be lost or not function properly.
        IEEE Xplore requires cookies to maintain sessions and to access licensed content. Cookies are used temporarily to maintain sessions in 
        IEEE Xplore and for no other purpose.'''

        Index2 = '''Internet Explorer 6, 7, or 8
        Click Tools menu.
        Select Internet Options.
        Select Privacy tab. 
        Click the Default button or slide the bar down to 'Medium'.
        Click Ok. '''

我希望能够为其提供键值Index1并在其后获取字符串块或迭代所有索引值并获取它们之后的块。我似乎无法从字符串中读取多行

到目前为止,我试过

for line in fileinput.input('config.conf'):
    part = line.partition("'''")
    ts = part[0]
    st = part[1]

1 个答案:

答案 0 :(得分:1)

解决问题的一种方法是使用像

这样的config.ini文件
[Multiline Values]
Index1 : You have been redirected to this page for one of the following
    reasons:
    Either cookies are not enabled on your browser
    or
    Your network configuration is causing cookies to be lost or not function properly.
    IEEE Xplore requires cookies to maintain sessions and to access licensed content. Cookies are used temporarily to maintain sessions in
    IEEE Xplore and for no other purpose.

并阅读如下:

import ConfigParser
Config = ConfigParser.ConfigParser()
Config.read('config.ini')
val = Config.get('Multiline Values', 'Index1')
print val

输出:

You have been redirected to this page for one of the following
reasons:
Either cookies are not enabled on your browser
or
Your network configuration is causing cookies to be lost or not function properly.
IEEE Xplore requires cookies to maintain sessions and to access licensed content. Cookies are used temporarily to maintain sessions in
IEEE Xplore and for no other purpose.

标题名称“多行值”和键名“Index1”可以是任何内容。