Найти - Пользователи
Полная версия: config parser ошибка при чтении
Начало » Python для новичков » config parser ошибка при чтении
1
Guljaca
В скрипте ниже должны записываться данные из файла конфигурации в словарь классов. Проблема в том, что в результате во всех классах прописываются данные из последней секции.

N=q

N=y
В обоих классах в данных пропишется N=y

[code python]  import ConfigParser, os

def absolutepath(opfile):
config = ConfigParser.SafeConfigParser()
scriptDirectory = os.path.dirname(os.path.realpath(__file__))
settingsFilePath = os.path.join(scriptDirectory, opfile)
config.readfp(open(settingsFilePath,"r"))
return config
print 'import', opfile

def writedata(ndict,nclass,namefile):
opfile=absolutepath(namefile)
for section in opfile.sections():
ndict[section]=nclass
for option in opfile.options(section):
ndict[section].options[option]=opfile.get(section,option)
print section,ndict[section].options [/code]
terabayt
я предполагаю что вы в функцию writedata параметром nclass передаете объект (экземпляр класса)
это тоже самое если бы вы делали так
 def writedata(ndict,nclass,namefile):
    opfile=absolutepath(namefile)
    for section in opfile.sections():
            for option in opfile.options(section):
                nclass.options[option]=opfile.get(section,option)
            print section,nclass.options
а если вы хотите
Guljaca
должны записываться данные из файла конфигурации в словарь классов
то нужно так
 # . . .
class A:
    # . . .
def writedata(ndict,nclass,namefile):
    opfile=absolutepath(namefile)
    for section in opfile.sections():
            ndict[section]=nclass()
            for option in opfile.options(section):
                ndict[section].options[option]=opfile.get(section,option)
            print section,ndict[section].options 
writedata({}, A, ‘namefile.txt’)


вот пример
так делаете вы
 class A:
    def __init__(self):
        self.options = {}
ndict = {}
def f(d, c):
    for i in range(3):
        d[i] = c
        for j in range(i, 5):
            d[i].options[j] = j*2-i
    return d
t = f(ndict, A())
for i, j in t.items():
    print(i, j.options)
0 {0: 0, 1: 1, 2: 2, 3: 4, 4: 6}
1 {0: 0, 1: 1, 2: 2, 3: 4, 4: 6}
2 {0: 0, 1: 1, 2: 2, 3: 4, 4: 6}
а так нужно
 class A:
    def __init__(self):
        self.options = {}
ndict = {}
def f(d, c):
    for i in range(3):
        d[i] = c()  # с скобками
        for j in range(i, 5):
            d[i].options[j] = j*2-i
    return d
t = f(ndict, A)  # без скобок
for i, j in t.items():
    print(i, j.options)
0 {0: 0, 1: 2, 2: 4, 3: 6, 4: 8}
1 {1: 1, 2: 3, 3: 5, 4: 7}
2 {2: 2, 3: 4, 4: 6}
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB