Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
694 views
in Technique[技术] by (71.8m points)

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

Can I change default open() (io.open() in 2.7) text encoding in a cross-platform way?

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...