UnicodeEncodeError in csv writer in Python

Today I was writing a program that generates a csv file after some processing. But I got the following error while trying on some test data:
writer.writerow(csv_li)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xbf' in position 5: ordinal not in range(128)
I looked into the documentation of csv module in Python and found a class named UnicodeWriter. So I changed my code to
writer = UnicodeWriter(open("filename.csv", "wb"))
Then I tried to run it again. It got rid of the previous UnicodeEncodeError but got into another error.
self.writer.writerow([s.encode("utf-8") for s in row])
AttributeError: 'int' object has no attribute 'encode'
So, before writing the list, I had to change every value to string.
row = [str(item) for item in row]
I think this line can be added in the writerow function of UnicodeWriter class.

Comments

Popular posts from this blog

Python all any built-in function

Accept-Encoding 'gzip' to make your cralwer faster

lambda magic to find prime numbers