0

I'm trying to write a python program using PyCharm and Python 3.3. 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.

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:

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

What am I doing wrong?

Ghost93
  • 165
  • 1
  • 2
  • 12

1 Answers1

2

You need to use the .read_file() method on your config instance instead:

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.

Alternatively, pass in the filename and encoding to .read() without opening the file yourself:

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

If your input file contains a UTF-8 BOM (\ufeff, a Microsoft devation from the UTF-8 standard) either create the file using a tool that doesn't add that character (e.g. not Notepad), use the utf_8_sig codec to open it:

config = configparser.ConfigParser()
config.read('RecorderMover.config.ini', encoding='utf-8-sig')
Martijn Pieters
  • 889,049
  • 245
  • 3,507
  • 2,997
  • @Ghost93: You created that file with an editor that adds a UTF-8 BOM. That character is redundant in UTF-8 files and should be removed, really. – Martijn Pieters Apr 02 '13 at 12:48
  • Thank you very much for your help! It worked! If anyone else wants to know what's BOM - [link](http://stackoverflow.com/questions/2223882/whats-different-between-utf-8-and-utf-8-without-bom) – Ghost93 Apr 02 '13 at 12:52