python - UnicodeDecodeError: while writing into a file -
i error while writing file. how can handle this.
traceback (most recent call last): file "c:\python27\aureusbaxprojectfb.py", line 278, in <module> rows = [[unicode(x) x in row] row in outlist] unicodedecodeerror: 'ascii' codec can't decode byte 0xe0 in position 0: ordinal not in range(128) >>>
code writing file
class unicodewriter: """ csv writer write rows csv file "f", encoded in given encoding. """ def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds): # redirect output 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") s in row]) # fetch utf-8 output queue ... data = self.queue.getvalue() data = data.decode("utf-8") # ... , reencode target encoding data = self.encoder.encode(data) # write target stream self.stream.write(data) # empty queue self.queue.truncate(0) def writerows(self, rows): row in rows: self.writerow(row) open('c:/users/desktop/fboutput.csv', 'wb') f: writer = unicodewriter(f) rows = [[unicode(x) x in row] row in outlist] writer.writerows(rows)
i using beautifulsoup parse html data , thats working fine. error while writing file.
unicode() constructor defined unicode(string[, encoding, errors])
, encoding has default ascii. if multi-byte string in outlist, should appoint unicode encode utf-8.
Comments
Post a Comment