Ascii codec can't decode character

Hi everyone.
We are receiving more and more files that contain fonts in the layers names or in the file name that cause me this message:


Do you have any solution to avoid this?

Hello.

What does line 41 of your script say? What are the important bits before and after?

Graham

40 file = open(finalPath, β€œa+”)
41 file.write("[layers]" β€˜\n’ + β€˜\n’.join(layerList))
42 file.close()

You probably should start using utf-8 instead of ascii, especially in a multiliingual environment.

2 Likes

Try adding # coding: utf-8 as the very first line of your script : does that fix it?

You need to import the codecs module so you can set the encoding to utf-8 to read and write unicode files.

Here’s a simple example which combines a Chinese character with good ol’ Hello World, writes it to a file and reads it back:

import codecs
f = codecs.open('test.txt', encoding='utf-8', mode='w+')
f.write(u'\u4500Hello World\n')
f.seek(0)
for line in f:
    print repr (line)
f.close()

Regards
Jeremy

1 Like

It works, thank you!
it was easier than I thought :slight_smile:

1 Like

By the way it is a good idea to use a context manager when reading or especially writing files to avoid leaving corrupted or blocked files on your system:

with open(finalPath, β€œa+”) as file:
    file.write("[layers]" β€˜\n’ + β€˜\n’.join(layerList))

# file is closed automatically 
1 Like