使用 configparser 读取 INI 文件时出错

Error when reading INI file using configparser

这是我的 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'

如果我 运行 以交互方式使用相同的代码,它就可以工作。但是,如果它与文件路径有关,则错误会有所不同,我假设:"file does not exist"。交互式:

>>> print(INI_fileName)
parameters.ini
>>> config.read('INI_fileName')
[]
>>> config.read('parameters.ini')
['parameters.ini']
>>> 

为什么不提取文件名?

在玩交互式命令时,我想我找到了原因。因为我使用文件名作为变量,所以我不需要使用引号!我的天啊... config.read(INI_fileName)

此问题可能是由于 Windows 文本编辑器添加的 UTF 字节顺序标记 (BOM) 引起的。

在读取 Linux/Unix 中的配置参数之前应删除 BOM。

尝试:

config = configparser.ConfigParser()
config_file_path = '/app/config.ini'  # full absolute path here!
s = open(config_file_path, mode='r', encoding='utf-8-sig').read()
open(config_file_path, mode='w', encoding='utf-8').write(s)
config.read(config_file_path)
# now check if it is OK