Rob
Rob

Reputation: 172

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.

Upvotes: 1

Views: 3898

Answers (4)

JyotiGrover
JyotiGrover

Reputation: 93

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

Upvotes: 3

David Scarlett
David Scarlett

Reputation: 3341

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

Upvotes: 4

Niranjan
Niranjan

Reputation: 1

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]

Upvotes: 0

Colwin
Colwin

Reputation: 2685

Since these are getting read in as a string, you should be able to do this and store it in a list

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

Upvotes: 2

Related Questions