Python编码写入文件时出错

时间:2017-10-11 19:47:16

标签: python encoding decoding

我想写一些不是英文的文件的字符串,它们是阿塞拜疆语。即使我执行utf-8编码,也会出现以下错误:

UnicodeEncodeError: 'ascii' codec can't encode characters in position 10-12: ordinal not in range(128)

我想写入文件的代码片段如下:

        t_w = text_list[y].encode('utf-8')
        new_file.write(t_w.decode('utf-8'))
        new_file.write('\n')

编辑

即使我将代码设为:

        t_w = text_list[y].encode('ascii',errors='ignore')
        new_file.write(t_w)
        new_file.write('\n')

我收到以下错误:

TypeError: write() argument must be str, not bytes

1 个答案:

答案 0 :(得分:0)

据我所知,t_w.decode(...)尝试将您的字符转换为ASCII,而ASCII不会对某些阿塞拜疆字符进行编码。无需解码字符串,因为您希望将其作为UTF-8写入文件,因此省略.decode(...)部分:new_file.write(t_w)