Pergunta

EDIT - I have managed to find a solution to my problem, answered at the bottom of the page.

I have a .ini file which contains a unknown amount of variables, created by a python script through a IRC interface.

The format of the .ini file is as follows:

[varables]
0 = example
1 = example2
2 = exapmle3
#and so on.

What i want to do with the varables in the .ini file is append each individual varable in the .ini file into a list.

This is a the code in the main Python file that i'm using to try and accomplish this with: (not the entire file, but what's being used to do this task.)

import ConfigParser
import os

#Config parser: 
class UnknownValue(Exception): pass
def replace_line(old_line, new_line):
    f = open("setup.ini")
    for line in f:
        line = os.linesep.join([s for s in line.splitlines() if s])
        if line == old_line:
            f1 = open("setup.ini",'r')
            stuff = f1.read()
            f1.close()
            new_stuff = re.sub(old_line,new_line,stuff)
            f = open("setup.ini",'w')
            f.write(new_stuff)
            f.close()        
def get_options(filename):
    config = ConfigParser.ConfigParser()
    try:
        config.read(filename)
    except ConfigParser.ParsingError, e:
        pass
    sections = config.sections()
    output = {}
    for section in sections:
        output[section] = {}
        for opt in config.options(section):
            value = config.get(section, opt)
            output[section][opt] = value
    return output

bot_owners = []#this becomes a list with every varable in the .ini file.


#gets the number of varables to be set, then loops appending each entry into their corosponding lists for later use.
setup_file = get_options("owner.ini")
num_lines = (sum(1 for line in open('owner.ini'))-1)#gets amount of varables in the file, and removes 1 for the header tag.
print "lines ", num_lines
x = 0
while x != num_lines:
    #loops through appending all the varables inside of the .ini file to the list 'bot_owners'
    y = str(x)
    bot_owners.append(setup_file['owners'][y])#this fails becuase it can't take a varable as a argument?
    x += 1

print (bot_owners)
print (num_lines)

I find out the number of varables in the .ini file using this line:

num_lines = (sum(1 for line in open('owner.ini'))-1)#gets amount of varables in the file, and removes 1 for the header tag.

i could append each vararable in the .ini file to the list by doing this:

bot_owners.append(setup_file['owners']['0'])
bot_owners.append(setup_file['owners']['1'])
bot_owners.append(setup_file['owners']['2'])
#ect

but this requries me to know the number of varables in the .ini file, which i cannot know, and it would be silly to try and it like this, as it imposes a limit on the amount of varables the .ini file could contain, and it reqires a ton of code that could be made far less.

if num_lines == 1:    
    bot_owners.append(setup_file['owners']['0'])
elif num_lines == 2:
    bot_owners.append(setup_file['owners']['1'])
elif num_lines == 3:
    bot_owners.append(setup_file['owners']['2'])
#ect

What's wrong with this code though, is with my loop:

x = 0 #what varable is going to be appended
while x != num_lines:
    #loops through appending all the varables inside of the .ini file to the list 'bot_owners'
    y = str(x)
    bot_owners.append(setup_file['owners'][y]) #<-- THE PROBLEM
    x += 1

The bot_owners.append(setup_file['owners'][y]) line brings up the folowing error:

KeyError: '0'

After looking about on the documentaion for Python's configParser libary, if i'm correct, this error is caused by the 2'nd argument [y] becuase a varable can't be used as an argument, even if the varable contains a string that could be "1", yet bot_owners.append(setup_file['owners']["1"]) works.

What i'm asking here, is if there is another way to do this, or how i could use a loop to append each individual varable inside of a .ini file into a list.

Foi útil?

Solução

Unfortunately, ConfigParser doesn't really support lists natively.

If there is a character you can safely use as a delimiter, an OK workaround is to pack the list into a delimited string and then unpack the string when you read your config file.

For comma delimiter:

[MYSECTION]
mylist = item1,item2,item3

Then use config.get('MYSECTION', 'mylist').split(',') in the client code.

Multiline options are also allowed. Then it would be something like

[MYSECTION]
mylist = 
    item1
    item2

And you would use str.splitlines() in the client code.

Outras dicas

After actually playing around with Python for a bit longer and reading through all the documentation in ConfigParser. I managed to find out how to do this without the line seperator as suggested.

If i had a .ini file like this:

[things]
1 = not relavant at all
[more_things]
42 = don't need this
[owners]
1 = test
2 = tesing123

I could append all the stored varables under [owners] using this.

import ConfigParser

config = ConfigParser.ConfigParser()
#File with the owner varables stored.
config.read('test.ini')
bot_owners = []

#Make sure the data is under the correct header.
if config.has_section('owners') == True:
    #find all the options under the [owners] header.
    data_points = config.options('owners')

    #Append the value assigned to the options to bot_owners
    for var in data_points:
        bot_owners.append(config.get('owners', var))

print bot_owners

Thus returning bot_owners as ['test', 'tesing123']

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top