【问题标题】:Error when reading INI file using configparser使用 configparser 读取 INI 文件时出错
【发布时间】:2020-04-28 01:35:08
【问题描述】:

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

为什么不拾取文件名?

【问题讨论】:

  • 您是否检查过 ini 文件是否以 BOM 开头?有时 BOM 会导致类似这样的奇怪错误,尤其是来自 Windows 的文件。

标签: python-3.x configparser


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    此问题可能是由于 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
    

    【讨论】:

      猜你喜欢
      • 2013-03-23
      • 2022-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多