将亚洲字符写入文件时的UnicodeEncodeError

时间:2016-03-26 01:48:04

标签: python python-3.x encoding

在尝试将亚洲字符写入文件时,我一直在遇到此错误 - 我可以在IDLE中打印字符(虽然不在命令行中)但是当我尝试编写它们时到一个文件,我收到这个错误:

Traceback (most recent call last):
  File "C:\Users\Tai\Desktop\Development\playlistcreator\main.py", line 21, in <module>
    playlistcreator.addtoplaylist(list_of_paths,"C:\\Users\\Tai\\Desktop\\New Music\\testplaylist.m3u8")
  File "C:\Users\Tai\Desktop\Development\playlistcreator\playlistcreator.py", line 74, in addtoplaylist
    playlistFile.write(track + '\n')
  File "C:\Users\Tai\AppData\Local\Programs\Python\Python35-32\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 56-57: character maps to <undefined>

认为了解错误是什么:基本上它不能渲染亚洲字符,所以它不能将它们写入文件 - 但如果我可以在IDLE中打印它们,为什么它不能将它们写入文件?有没有办法解决这个问题?

(我不确定代码是否有必要了解错误,但无论如何我都会将其发布)

def addtoplaylist(paths, playlist_path):
    # Open file (or create if it does not exist)
    #change to given directory
    try:
        os.chdir(os.path.dirname(paths))
    except Exception as err:
        print(err)
    #open file - if it does not exist, create it
    with open(os.path.basename(playlist_path), 'a+') as playlistFile:
        for track in paths:
            playlistFile.write(track + '\n')
    playlistFile.close()

2 个答案:

答案 0 :(得分:0)

您需要在打开文件时指定文件的编码,例如:

with open(os.path.basename(playlist_path), 'a+', encoding='UTF-8') as playlistFile:

否则,Python默认使用控制台编码(ANSI)作为文件,在本例中为CP 1252,这是扩展Latin-1的Windows名称。

答案 1 :(得分:-1)

您需要使用适合字符的编码。

playlistFile.write(track.encode(encoding=some_encoding) + '\n')

我猜some_encode = 'utf-8'会做但不太确定。

也许IDLE默认使用不同的编码,这就是它在那里工作的原因。