用Python读取.ini文件

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

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

class iniConfig:

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

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

输出:

     File cannot be opened!

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

谢谢,

3301

python ini
1个回答
0
投票

您应在以下几行中指定.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 documentation中with语句的更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.