用Python阅读.ini文件

问题描述 投票:0回答:1

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

class iniConfig:

def __init__(self):
    self.iniConfig = ConfigParser(allow_no_value=True)
    f = open('The_Path_to_ini', 'r')
    print(self.iniConfig.read('The_Path_to_ini'))
    print("Sections: ", self.iniConfig.sections())

输出:

FileNotFoundError: [Errno 2] No such file or directory: 
The_Path_to_ini

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

谢谢,

3301

python ini
1个回答
0
投票

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

    f = open('The_Path_to_ini', 'r')

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

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

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

try:
   f = open('file', 'r')
   ...
except OSError:
   print('File cannot be opened!')
© www.soinside.com 2019 - 2024. All rights reserved.