【问题标题】:Ascii error when trying to write in file open with codecs lib尝试写入使用编解码器库打开的文件时出现 Ascii 错误
【发布时间】:2014-08-29 12:18:57
【问题描述】:

代码

# -*- coding: ISO-8859-15 -*-
import sys
import codecs
filename2 = "log_unicode2.log"
log_file2 = codecs.open(filename2, "w", "utf-8")
sys.stdout = log_file2
log_file2.write('aééé')

错误

Traceback (most recent call last):
  File "snippet_problem_unicode.py", line 7, in <module>
    log_file2.write('a├®├®├®')
  File "C:\Users\dev1\Envs\atao\lib\codecs.py", line 691, in write
    return self.writer.write(data)
  File "C:\Users\dev1\Envs\atao\lib\codecs.py", line 351, in write
    data, consumed = self.encode(object, self.errors)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 1: ordinal
not in range(128)

上下文

  • Windows 7
  • Python 2.6
  • 日食

'aééé' 是一个字节串(latin-1),需要转换为 utf-8。 为什么这个转换涉及到 ascii 编解码器?

【问题讨论】:

    标签: python utf-8 ascii


    【解决方案1】:

    您正在将 字节字符串 写入文件对象,需要 unicode。要从字节字符串转换为 unicode 值,Python 必须对字节字符串进行解码。此解码使用默认的 ASCII 编解码器。

    要么:

    1. 使用 unicode 文字而不是字节字符串:

      log_file2.write(u'aééé')
      
    2. 首先使用您的源文件编码将字节串显式解码为 Unicode:

      log_file2.write('aééé'.decode('latin1'))
      
    3. 不使用codecs.open(),而是使用内置的open()函数打开文件,然后手动解码,然后编码为UTF:

      log_file2 = open(filename2, "w")
      log_file2 .write('aééé'.decode('latin1').encode('utf8')
      

      或使用unicode 文字并手动编码:

      log_file2 = open(filename2, "w")
      log_file2 .write(u'aééé'.encode('utf8'))
      

    【讨论】:

    • 换一种说法:一个字节串隐含地是以前的 ascii 编码的结果,并由编解码器库按原样解码。
    • @LBarret:一个字节串可能包含文本信息。尝试将其用作 Unicode 文本时,将假定它使用 ASCII 编解码器对其进行解码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-15
    • 2017-07-30
    • 2013-02-06
    • 2020-02-03
    • 1970-01-01
    • 2020-11-17
    • 1970-01-01
    相关资源
    最近更新 更多