【问题标题】:Python ConfigParser QuestionPython ConfigParser 问题
【发布时间】:2012-05-26 03:15:59
【问题描述】:

ConfigParser 的配置文件是否必须命名为“Config.ini”才能工作?

我希望名称为“1Config.ini”,以便它出现在文件夹目录的顶部。

这是我目前拥有的

config = ConfigParser.ConfigParser()
config.read(Revision[0:Revision.rfind('\\')] + "\1Config.ini")

Type = config.get("myvars", "Type")

但是当文件和代码被命名为“1Config.ini”时,我得到了这个错误

<class 'ConfigParser.NoSectionError'>: No section: 'myvars'

【问题讨论】:

  • 你应该在 Stack Overflow 上问这个。
  • 你的权利!我实际上打开了两个窗口并张贴在错误的窗口中......我的错
  • 重命名配置文件只是为了让它们显示在顶部似乎有点轻率。我的意思是,如果他们按字母升序以外的方式排序怎么办?
  • 您还需要转义该反斜杠或最好使用os.path.join
  • 虽然如果找不到文件似乎会弹出该错误,但它表示您的部分不存在。大概您已经这样做了,但我建议您确保正确指定该部分(并且大写计数!)。

标签: arcgis python


【解决方案1】:

下面的输出是什么?确保它是一个有效的文件名。

>>> print Revision[0:Revision.rfind('\\')] + "\1Config.ini"

最好使用os.path.join 而不是串联字符串:

import os
filename = os.path.join(Revision[0:Revision.rfind('\\')], "Config.ini")
config.read(filename)

您可能不应该将变量命名为Type,因为type 是一个内置函数/模块,它会让人困惑。

Type = config.get("myvars", "Type")

不,配置文件可以任意命名:

>>> a = ConfigParser.ConfigParser()
>>> a.read("E:/Documents/2012/config.test") # where config.test is the example from the documentation
['E:/Documents/2012/config.test']
>>> a.sections()
['My Section']
>>> a.items(a.sections()[0])
[('foodir', 'frob/whatever'),
 ('dir', 'frob'),
 ('long', 'this value continues\nin the next line')]

【讨论】:

    猜你喜欢
    • 2023-02-02
    • 2014-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多