【问题标题】:Read a comma separated ini file in python?在python中读取逗号分隔的ini文件?
【发布时间】:2017-11-16 01:01:11
【问题描述】:

我有一个ini文件

[default]
hosts=030, 031, 032

我有一个逗号分隔的值。我可以用一个简单的

读取整个值
comma_separated_values=config['default']['hosts']

这样我可以获取变量中的所有值。但是我怎样才能遍历这个 INI 文件,以便我可以将所有这些值存储为一个列表而不是变量。

【问题讨论】:

标签: python ini


【解决方案1】:

假设值必须是整数,您可能希望在从逗号分隔的字符串中提取列表后将它们转换为整数。

从 Colwin 的回答开始:

values_list = [int(str_val) for str_val in config['default']['hosts'].split(',')]

或者如果每个数字的零前缀应该表示它们是八进制:

values_list = [int(str_val, 8) for str_val in config['default']['hosts'].split(',')]

【讨论】:

  • 谢谢@David,上面的答案正是我想要的……当我阅读 INI 文件时,它被存储为 unicode 类型,但你的代码帮助我将它们存储为int 也可以作为列表。感谢您的帮助。
【解决方案2】:

由于这些是作为字符串读入的,因此您应该能够执行此操作并将其存储在列表中

values_list = config['default']['hosts'].split(',')

【讨论】:

    【解决方案3】:

    你可以概括如下:

    import ConfigParser
    import io
    
    # Load the configuration file
    def read_configFile():
        config = ConfigParser.RawConfigParser(allow_no_value=True)
        config.read("config.ini")
        # List all contents
        print("List all contents")
        for section in config.sections():
            #print("Section: %s" % section)
            for options in config.options(section):
                if (options == 'port'):
                    a = config.get(section,options).split(',')
                    for i in range(len(a)):
                        print("%s:::%s" % (options,  a[i]))
    
                else:
                    print("%s:::%s" % (options,  config.get(section, options)))
    
    read_configFile()
    
    
    config.ini
    [mysql]
    host=localhost
    user=root
    passwd=my secret password
    db=write-math
    port=1,2,3,4,5
    
    [other]
    preprocessing_queue = ["preprocessing.scale_and_center",
    "preprocessing.dot_reduction",
    "preprocessing.connect_lines"]
    
    use_anonymous=yes
    

    【讨论】:

      【解决方案4】:

      您可以读取文件的内容并使用 split(',') 将其拆分。用下面的代码试试吧。

      with open('#INI FILE') as f:
          lines = f.read().split(',')
      print(lines) # Check your output
      print (type(lines)) # Check the type [It will return a list]
      

      【讨论】:

      • 发帖人表示他们可以通过config['default']['hosts']访问逗号分隔值的字符串。这表明他们已经解析了 INI 文件(可能使用类似 ConfigParser 模块的东西),尝试通过 file.read() 函数将文件解析为无格式文本将是一个重大的倒退。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多