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

问题描述 投票:2回答:2

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

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

.ini文件的格式如下:

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

我想对.ini文件中的变量执行的操作是将.ini文件中的每个单独变量追加到列表中。

这是主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'nd参数引起的[y]因为varable不能用作参数,即使varable包含一个字符串可能是“1”,但bot_owners.append(setup_file ['owner'] [“1”])有效。

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

python loops ini configparser
2个回答
3
投票

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

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

对于逗号分隔符:

[MYSECTION]
mylist = item1,item2,item3

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

还允许多行选项。那就像是

[MYSECTION]
mylist = 
    item1
    item2

你会在客户端代码中使用str.splitlines()


0
投票

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

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

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

我可以使用这个在qazxsw poi下附加所有存储的变量。

[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

© www.soinside.com 2019 - 2024. All rights reserved.