set local to utf8 in python

To set the encoding to UTF-8 in Python, you can use the sys module to set the default encoding. Here is how you can do it:

main.py
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
55 chars
4 lines

Alternatively, you can specify the encoding when you open a file using the io module:

main.py
import io
with io.open('file.txt', 'r', encoding='utf-8') as f:
    # Read the file with UTF-8 encoding
    content = f.read()
127 chars
5 lines

Remember, Python 3 strings are already unicode, so you don't need to worry about encoding for in-memory strings.

related categories

gistlibby LogSnag