2

I have a two dimensional array which has Russian/Arabic/ Chinese characters in it. I am not sure how to print all of it to a CSV file. I would like to print it to the CSV in UTF-8. The code which I am using is listed below.

matchedArray = [[]]
matchedArray.append(x)

ar = matchedArray

f1 = open('C:/Users/sagars/Desktop/encoding.csv','w')
writer = csv.writer(f1)
writer.writerow(['Flat Content', 'Post Dates', 'AuthorIDs', 'ThreadIDs',
                 'Matched Keyword', 'Count of keyword']) #if needed
for values in ar:
    writer.writerow(values)

However, I am getting the following error:

Traceback (most recent call last):
  File "C:/Users/sagars/PycharmProjects/encoding/encoding.py", line 18, in <module>
    writer.writerow(values)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 3-13: ordinal not in range(128)

Process finished with exit code 1

How can I print this 2D array to the CSV file?

Thanks!

Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
Sagar Samtani
  • 203
  • 1
  • 4
  • 10

1 Answers1

1

You can use the str.encode to encode each character using the right encoding before storing to the csv file.

for values in ar:
    # values is a list/string of unicode characters
    writer.writerow([val.encode("utf-8") for val in values])   
Prashanth
  • 1,252
  • 2
  • 13
  • 28