这是我的ini文件parameters.ini:
[parameters]
Vendor = Cat
这是我的python代码:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import codecs
import sys
import os
import configparser
### Script with INI file:
INI_fileName="parameters.ini"
if not os.path.exists(INI_fileName):
print("file does not exist")
quit()
print("Here is the INI_fileName: " + INI_fileName)
config = configparser.ConfigParser()
config.read('INI_fileName')
vendor = config['parameters']['Vendor']
print("Here is the vendor name: " + vendor)
这里是错误:
python3 configParser-test.py
Here is the INI_fileName: parameters.ini
Traceback (most recent call last):
File "configParser-test.py", line 18, in <module>
vendor = config['parameters']['Vendor']
File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/configparser.py", line 958, in __getitem__
raise KeyError(key)
KeyError: 'parameters'
如果我以交互方式运行相同的代码,它将起作用。但是,如果它与文件路径有关,则错误会有所不同,我假设:“文件不存在”。互动式:
>>> print(INI_fileName)
parameters.ini
>>> config.read('INI_fileName')
[]
>>> config.read('parameters.ini')
['parameters.ini']
>>>
为什么不选择文件名?
[在玩交互式命令时,我想我找到了原因。由于我使用文件名作为变量,所以我不需要使用引号!我的天啊...config.read(INI_fileName)