0

我正在尝试使用 PyCharm 和 Python 3.3 编写一个 python 程序。我想要做的是我的程序会将文件从一个目录复制到一个文件夹或多个文件夹(取决于配置文件)。

由于我试图复制到文件的一些目录是希伯来语,所以 ini 文件是 utf-8。

但是,当我从该文件中读取配置时,这就是我得到的:

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:

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:

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

我究竟做错了什么?

4

1 回答 1

2

您需要在您的实例上使用该.read_file()方法:config

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

.read()方法将f其视为文件名序列,并且由于任何行都不能被解释为文件名,因此配置最终为空。

.read()或者,在不自己打开文件的情况下传入文件名和编码:

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

如果您的输入文件包含 UTF-8 BOM(\ufeff,来自 UTF-8 标准的 Microsoft 版本)或者使用不添加该字符的工具(例如,不是记事本)创建文件,请使用utf_8_sig编解码器打开它:

config = configparser.ConfigParser()
config.read('RecorderMover.config.ini', encoding='utf-8-sig')
于 2013-04-02T12:41:00.147 回答