简体   繁体   English

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

[英]Read a comma separated INI file in python?

I have an INI file我有一个 INI 文件

[default]
hosts=030, 031, 032

where I have comma separated values.我有逗号分隔的值。 I can read all values with a simple我可以用一个简单的方法读取所有值

comma_separated_values=config['default']['hosts']

This way I can get all the values in a variable.这样我就可以获得变量中的所有值。 But how can I iterate over this INI file so that I can store all these values as a list rather variable.但是我怎样才能遍历这个 INI 文件,以便我可以将所有这些值存储为一个列表而不是变量。

Assuming the values are required to be integers, you would want to convert them to integers after extracting a list from the comma-separated string.假设这些值必须是整数,您可能希望在从逗号分隔的字符串中提取列表后将它们转换为整数。

Following on from Colwin's answer:继科尔文的回答之后:

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

Or if the zero prefixes to each number are supposed to indicate that they are octal:或者,如果每个数字的零前缀应该表示它们是八进制:

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

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

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

You can generalize it as follows :您可以将其概括如下:

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

You can read the contents of the file and split it using split(',').您可以读取文件的内容并使用 split(',') 将其拆分。 Try it using the below code.尝试使用下面的代码。

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM