1
output_file = open(OUTPUT_FILENAME,'w',newline='') #create new file
dict_writer = csv.DictWriter(output_file, keys)
dict_writer.writeheader()
#some logic
for row in items:
    #di dictionary
    dict_writer.writerow(di)

Hello, I am new to python. I created this script on Linux (centos) I ran it and it works fine, I tried running it on windows I got this error

Traceback (most recent call last):
  File "C:\Users\user157\Desktop\test.py", line 180, in <module>
    dict_writer.writerow(di)
  File "C:\Users\user157\AppData\Local\Programs\Python\Python38-32\lib\csv.py", line 154, in writerow
    return self.writer.writerow(self._dict_to_list(rowdict))
  File "C:\Users\user157\AppData\Local\Programs\Python\Python38-32\lib\encodings\cp1256.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\xe3' in position 33: character maps to <undefined>

I tried solving it by using before I write the dictionary but still same error

for k,v in di.items():
    try:
        di[k] =v.encode().decode('utf-8')
    except:
        pass

I have python 3.7.5 on centos and 3.8.2 on windows

1 Answer 1

1

You need to check what your input file encoding is in Windows and use encoding='' in your input file open statement. In windows the default ending is not 'utf8' and therefore will have encoding issues if not opened with correct encoding like below,

open(input_file_name,encoding='iso-8859-1')

or better change your input file to 'utf8' encoding, so that the script can be used without modification on windoes and in linux.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.