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

标签 python loops ini configparser

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

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

.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['owners'][y]) 行会出现以下错误:

KeyError: '0'

查看 documentaion 后对于Python的configParser库,如果我是正确的,这个错误是由第二个参数[y]引起的,因为变量不能用作参数,即使变量包含字符串可能是“1”,但 bot_owners.append(setup_file['owners']["1"]) 有效。

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

最佳答案

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

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

对于逗号分隔符:

[MYSECTION]
mylist = item1,item2,item3

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

也允许多行选项。那么它会是这样的

[MYSECTION]
mylist = 
    item1
    item2

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

关于python - 使用循环在 .ini 文件中分配已知数量的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15081687/

相关文章:

python - cygwin下安装python ldap模块

python - PyQt4 QTimer 不起作用

python - 如何使 Kivy 屏幕的一部分可滚动

java - 在Java中,试图打印一个整数中有多少位数字平均分为整个整数

php - "invalid data source name"与 PDO MySQL

PHP:为一个文件而不是 php.ini 设置 max_file_uploads

java - 无法在 Java API 中运行 Tensorflow 预测

c - 在 C 中制作一个看起来不错的 REPL

c - c 中带有 while 循环的数字三角形

c++ - 将字符串值转换为标准字符串