【问题标题】:Reading .ini files in Python在 Python 中读取 .ini 文件
【发布时间】:2020-04-04 10:42:29
【问题描述】:

我是 .ini 文件的新手,我试图用 python 读取 .ini 配置文件,但我被卡住了! 我已经尝试过这种方法,但它并没有真正为我工作:

类iniConfig:

def __init__(self):
    self.iniConfig = ConfigParser(allow_no_value=True)
    try:
        f = open('C://Desktop//PythonScripts//Config.ini', 'r')
        self.iniConfig.read(f)
        print("Sections: ", self.iniConfig.sections())

    except OSError:
        print('File cannot be opened!')

输出:

     Sections: []

我仍然不明白我做错了什么:(

提前谢谢你,

3301

【问题讨论】:

  • f = open('The_Path_to_ini', 'r') 行在这里没有意义。什么是“The_Path_to_ini”?
  • 创建一个标准格式的ini文件,保存为The_Path_to_ini。但如果我是你,我会把它改成一个更有意义的文件名。
  • 我已经创建了一个ini文件,我什至更改了整个代码,但问题从未解决。
  • 您似乎完全错过了最重要的一点。 它实际上叫The_Path_to_ini吗? 是你的代码试图打开的文件名。

标签: python ini


【解决方案1】:

您应该在这些行中指定 .ini 文件的实际路径,而不是 'The_Path_to_ini'

    f = open('The_Path_to_ini', 'r')
    print(self.iniConfig.read('The_Path_to_ini'))

处理open 调用中可能发生的异常也是一个好主意。根据open() 文档:

If the file cannot be opened, an OSError is raised.

您可以通过这种方式使用try ... except 块处理此异常:

try:
   f = open('file', 'r')
   ...
except OSError as e:
   print('File cannot be opened: ', e)

如果您不需要处理异常,通常使用with 语句而不是try ... except 块。例如:

with open('file', 'r') as f:
   # work with f

详细了解 Python 中的 with 语句documentation

【讨论】:

  • 是命令 self.iniConfig.read('The_Path_to_ini') 尝试加载 ini 文件。不需要open函数
  • 嘿,感谢您的重播,但即使我将绝对路径放入 .ini 文件,我仍然收到 OSError。
  • 谢谢,我在回答中添加了self.iniConfig.read()。我们不知道为什么要使用open 函数,我认为有关异常处理的信息可能很有用。
  • @3301 您的用户是否有足够的权限打开此文件?从命令行检查:stat -c %G:%A <filepath>.
  • 我确实有权打开文件(我希望如此)。我已经尝试了上述所有解决方案,但对我没有任何帮助:((
【解决方案2】:

您正在使用 open 打开文件,并使用 .read 接受路径,因此请尝试以下操作:

   def __init__(self):
      self.iniConfig = ConfigParser(allow_no_value=True)
      try:
          self.iniConfig.read('C://Desktop//PythonScripts//Config.ini')
          print("Sections: ", self.iniConfig.sections())

      except OSError:
          print('File cannot be opened!')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-29
    • 2014-09-17
    • 2017-11-16
    • 2013-04-18
    • 2015-10-02
    • 1970-01-01
    相关资源
    最近更新 更多