编辑 - 我设法找到了解决我的问题的方法,在页面底部得到了回答。
我有一个 .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 文件中的每个 vararable 附加到列表中:
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'
在查看Python 的 configParser 库的文档后,如果我是正确的,则此错误是由第二个参数[y]引起的,因为即使该变量包含一个字符串可能是“1”,但bot_owners.append(setup_file['owners']["1"])有效。
我在这里要问的是,是否有另一种方法可以做到这一点,或者我如何使用循环将 .ini 文件中的每个单独的变量附加到列表中。