Is there a way to change Python's open() default text encoding?

Don't change the locale or preferred encoding because;

  • it may affect other parts of your code (or the libraries you're using); and
  • it wont be clear that your code depends on open using a specific encoding.

Instead, use a simple wrapper:

from functools import partial
open_utf8 = partial(open, encoding='UTF-8')

You can also specify defaults for all keyword arguments (should you need to).


you can set the encoding ... but its really hacky

import sys
sys.getdefaultencoding() #should print your default encoding
sys.setdefaultencoding("utf8") #error ... no setdefaultencoding ... but...
reload(sys)
sys.setdefaultencoding("utf8")  #now it succeeds ...

I would instead do

main_script.py

import __builtin__
old_open = open
def uopen(*args, **kwargs):
    return open(*args, encoding='UTF-8', **kwargs)
__builtin__.open = uopen

then anywhere you call open it will use the utf8 encoding ... however it may give you errors if you explicitly add an encoding

or just explicitly pass the encoding any time you open a file , or use your wrapper ...

pythons general philosophy is explicit is better than implicit, which implies the "right" solution is to explicitly declare your encoding when opening a file ...