Can I change default open()
So that I didn't need to specify each time open(...,encoding='utf-8').
In text mode, if encoding is not specified the encoding used is platform dependent: locale.getpreferredencoding(False) is called to get the current locale encoding.
Though documentation doesn't specify how to set preferred encoding. The function is in locale module, so I need to change locale? Is there any reliable cross-platform way to set UTF-8 locale? Will it affect anything else other than the default text file encoding?
Or locale changes are dangerous (can break something), and I should stick to custom wrapper such as:
def uopen(*args, **kwargs):
return open(*args, encoding='UTF-8', **kwargs)
解决方案
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')
This has two other advantages:
You can specify defaults for all keyword arguments (should you need to).
You can override the defaults when calling the function.