简体   繁体   English

使用configparser从utf-8 .ini文件读取配置时的KeyError

[英]KeyError while reading configuration from utf-8 .ini file using configparser

I'm trying to write a python program using PyCharm and Python 3.3. 我正在尝试使用PyCharm和Python 3.3编写python程序。 What I want to do is that my program will copy files from one directory, to one folder or more (depending on the configuration file). 我想要做的是我的程序将文件从一个目录复制到一个或多个文件夹(取决于配置文件)。

Since some of the directories I am trying to copy to the files are in Hebrew, the ini file is utf-8. 由于我试图复制到文件的某些目录是希伯来语,因此ini文件是utf-8。

But, when I read the configuration from that file this is what I get: 但是,当我从该文件中读取配置时,这就是我得到的:

C:\Python33\python.exe C:/Users/Username/PycharmProjects/RecorderMover/RecorderMover.py
Traceback (most recent call last):
  File "C:/Users/Username/PycharmProjects/RecorderMover/RecorderMover.py", line 77, in <module>
    sourcePath, destPaths, filesToExclude = readConfig()
  File "C:/Users/Username/PycharmProjects/RecorderMover/RecorderMover.py", line 62, in readConfig
    config = config['RecorderMoverConfiguration']
  File "C:\Python33\lib\configparser.py", line 942, in __getitem__
    raise KeyError(key)
KeyError: 'RecorderMoverConfiguration'

RecorderMover.py: RecorderMover.py:

def readConfig():
    config = configparser.ConfigParser()

    with codecs.open('RecorderMover.config.ini', 'r', encoding='utf-8') as f:
        config.read(f)

    config = config['RecorderMoverConfiguration']

    sourcePath = config['SourcePath']
    destPaths = config['DestinationPaths']
    filesToExclude = config['FilesToExclude']

RecorderMover.config.ini: RecorderMover.config.ini:

[RecorderMoverConfiguration]
SourcePath=I:\VOICE\A
DestinationPaths=D:\RoseBackup,E:\רוזה
FilesToExclude=20.08.12.mp3

What am I doing wrong? 我究竟做错了什么?

You need to use the .read_file() method on your config instance instead: 您需要在config实例上使用.read_file()方法:

with open('RecorderMover.config.ini', 'r', encoding='utf-8') as f:
    config.read_file(f)

The .read() method treats f as a sequence of filenames instead, and as none of the lines could ever be interpreted as a filename, the configuration ends up empty. .read()方法将f视为一系列文件名,并且由于没有任何行可以被解释为文件名,因此配置结束为空。

Alternatively, pass in the filename and encoding to .read() without opening the file yourself: 或者,将文件名和编码传递给.read()而无需自己打开文件:

config = configparser.ConfigParser()
config.read('RecorderMover.config.ini', encoding='utf-8')

If your input file contains a UTF-8 BOM ( \ , a Microsoft devation from the UTF-8 standard) either create the file using a tool that doesn't add that character (eg not Notepad), use the utf_8_sig codec to open it: 如果您的输入文件包含UTF-8 BOM( \ ,Microsoft偏离UTF-8标准),则使用不添加该字符的工具(例如, 不是记事本)创建文件,使用utf_8_sig编解码器打开它:

config = configparser.ConfigParser()
config.read('RecorderMover.config.ini', encoding='utf-8-sig')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM