简体   繁体   中英

Read a comma separated INI file in python?

I have an INI file

[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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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