Pergunta

I am using this Python code to read a Windows INI file

from ConfigParser import SafeConfigParser

parser = SafeConfigParser()
parser.read('someinifile.ini')

for section_name in parser.sections():
    for name, value in parser.items(section_name):
        print '  %s = %s' % (name, value)
    lastkey = name

Works perfectly fine when I try to get the last keyname into a variable called "lastkey". But if you notice I am trying to read "name" variable outside of the "for name, value" loop. Is that illegal or incorrect? :-) I do get the last key name in lastkey but was wondering if I am doing something wrong here. I have an allergy towards badly written code so always prefer to clarify when in doubt. And I am totally new to Python too ",)

Foi útil?

Solução

If parser.items(section_name) is empty, name will never be initialized. You'll get a "NameError: name 'name' is not defined" exception when evaluating the line lastkey = name.

So don't forget to take into account the case where parser.items(section_name) is empty.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top