UnicodeDecodeError:写入文件时

时间:2013-09-04 03:37:26

标签: python python-2.7 unicode utf-8

写入文件时出现此错误。我该怎么办呢。

Traceback (most recent call last):
  File "C:\Python27\AureusBAXProjectFB.py", line 278, in <module>
    rows = [[unicode(x) for x in row] for row in outlist]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe0 in position 0: ordinal not in range(128)
>>> 

写入文件的代码

class UnicodeWriter:
    """
    A CSV writer which will write rows to CSV file "f",
    which is encoded in the given encoding.
    """

    def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
        # Redirect output to a queue
        self.queue = cStringIO.StringIO()
        self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
        self.stream = f
        self.encoder = codecs.getincrementalencoder(encoding)()

    def writerow(self, row):
        self.writer.writerow([s.encode("utf-8") for s in row])
        # Fetch UTF-8 output from the queue ...
        data = self.queue.getvalue()
        data = data.decode("utf-8")
        # ... and reencode it into the target encoding
        data = self.encoder.encode(data)
        # write to the target stream
        self.stream.write(data)
        # empty queue
        self.queue.truncate(0)

    def writerows(self, rows):
        for row in rows:
            self.writerow(row)

with open('C:/Users/Desktop/fboutput.csv', 'wb') as f:
    writer = UnicodeWriter(f)
    rows = [[unicode(x) for x in row] for row in outlist]
    writer.writerows(rows)

我正在使用BeautifulSoup来解析html数据,而且工作正常。我在写入文件时只收到错误。

1 个答案:

答案 0 :(得分:0)

unicode()构造函数定义为unicode(string[, encoding, errors]),编码默认为ascii。如果多字节字符串在outlist中,则应指定unicode编码,如utf-8。