Switching to Python 3 causing UnicodeDecodeError

前端 未结 3 1083
臣服心动
臣服心动 2020-11-27 05:04

I\'ve just added Python3 interpreter to Sublime, and the following code stopped working:

for directory in directoryList:
    fileList = os.listdir(directory)         


        
3条回答
  •  清酒与你
    2020-11-27 05:19

    Python 3 decodes text files when reading, encodes when writing. The default encoding is taken from locale.getpreferredencoding(False), which evidently for your setup returns 'ASCII'. See the open() function documenation:

    In text mode, if encoding is not specified the encoding used is platform dependent: locale.getpreferredencoding(False) is called to get the current locale encoding.

    Instead of relying on a system setting, you should open your text files using an explicit codec:

    currentFile = open(filename, 'rt', encoding='latin1')
    

    where you set the encoding parameter to match the file you are reading.

    Python 3 supports UTF-8 as the default for source code.

    The same applies to writing to a writeable text file; data written will be encoded, and if you rely on the system encoding you are liable to get UnicodeEncodingError exceptions unless you explicitly set a suitable codec. What codec to use when writing depends on what text you are writing and what you plan to do with the file afterward.

    You may want to read up on Python 3 and Unicode in the Unicode HOWTO, which explains both about source code encoding and reading and writing Unicode data.

提交回复
热议问题