在 python 中读取逗号分隔的 ini 文件?

Read a comma separated ini file in python?

我有一个 ini 文件

[default]
hosts=030, 031, 032

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

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

这样我就可以得到一个变量中的所有值。但是我如何遍历这个 INI 文件,以便我可以将所有这些值存储为一个列表而不是变量。

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

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

您可以读取文件的内容并使用 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]

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

继 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(',')]

您可以概括如下:

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