python 2.7 unicode writer robust to NoneType -
i hoping use unicodewriter the official examples not hiccup on unicode data when trying csv write. however, if have blanks/missing/nan in list should row, error:
self.writer.writerow([s.encode("utf-8") s in row]) attributeerror: 'nonetype' object has no attribute 'encode' is there easy fix?
i repeat 'official code' below:
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)
a previous question (though string conversion of numbers) solved problem too, see this answer. add conversion unicode: self.writer.writerow([unicode(s).encode("utf-8") s in row])
Comments
Post a Comment