简体   繁体   中英

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. I get an error only while writing into a file.

unicode() constructor defined as unicode(string[, encoding, errors]) and encoding has default is ascii. If multi-byte string is in outlist, you should appoint unicode encode like utf-8.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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