简体   繁体   English

UnicodeDecodeError:写入文件时

[英]UnicodeDecodeError: while writing into a file

I get this error while writing into a file. 写入文件时出现此错误。 How can I handle this. 我该如何处理。

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)
>>> 

Code for writing into a file 写入文件的代码

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)

I am using BeautifulSoup to parse the html data and thats working fine. 我正在使用BeautifulSoup解析html数据,多数民众赞成在正常工作。 I get an error only while writing into a file. 仅在写入文件时出现错误。

unicode() constructor defined as unicode(string[, encoding, errors]) and encoding has default is ascii. unicode()构造函数定义为unicode(string[, encoding, errors]) ,编码默认为ascii。 If multi-byte string is in outlist, you should appoint unicode encode like utf-8. 如果多字节字符串在列表中,则应指定utf-8这样的unicode编码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM