使用循环在.ini文件中分配已知数量的变量

时间:2013-02-26 05:00:28

标签: python loops ini configparser

编辑 - 我已设法找到问题的解决方案,在页面底部回答。

我有一个.ini文件,其中包含一个未知数量的变量,由python脚本通过IRC接口创建。

.ini文件的格式如下:

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

我想对.ini文件中的变量进行操作,将.ini文件中的每个varable附加到列表中。

这是主Python文件中的代码,我用它来尝试完成此任务:(不是整个文件,而是用于执行此任务的内容。)

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)

我使用以下行找出.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.

我可以通过执行以下操作将.ini文件中的每个可变量附加到列表中:

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

但这要求我知道.ini文件中的可变数量,这是我无法知道的,尝试这样做会很愚蠢,因为它对.ini文件的可变数量施加了限制可以包含,它需要大量的代码,可以做得更少。

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

使用此代码的错误 ,是我的循环

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

bot_owners.append(setup_file ['owner'] [y])行会显示以下错误:

KeyError: '0'

在查看了documentaion的Python的configParser库之后,如果我是正确的,这个错误是由第2个参数 [y] 引起的,因为varable不能用作参数,即使varable包含一个可能为“1”的字符串,但 bot_owners.append(setup_file ['owner'] [“1”])也可以。

我在这里要问的是,是否有另一种方法可以做到这一点,或者我如何使用循环将.ini文件中的每个varable附加到列表中。

2 个答案:

答案 0 :(得分:3)

不幸的是,ConfigParser本身并不真正支持列表。

如果有一个字符可以安全地用作分隔符,那么一个好的解决方法是将列表打包成一个分隔的字符串,然后在读取配置文件时解压缩字符串。

对于逗号分隔符:

[MYSECTION]
mylist = item1,item2,item3

然后在客户端代码中使用config.get('MYSECTION', 'mylist').split(',')

也允许使用多行选项。那就像是

[MYSECTION]
mylist = 
    item1
    item2

您可以在客户端代码中使用str.splitlines()

答案 1 :(得分:0)

在实际使用Python一段时间之后,阅读ConfigParser中的所有文档。我设法找到了如何在没有建议的行分隔符的情况下执行此操作。

如果我有这样的.ini文件:

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

我可以使用此功能在[owners]下附加所有存储的可变数据。

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

因此将bot_owners作为['test', 'tesing123']

返回