有没有办法改变Python的open()默认文本编码? [英] Is there a way to change Python's open() default text encoding?
问题描述
我可以更改默认 open()
( io.open()
in 2.7 )跨平台的文本编码?
我不需要每次指定 open(...,encoding ='utf-8')
。
< blockquote>
在文本模式下,如果未指定编码,则使用的编码取决于平台: locale.getpreferredencoding(False)
调用以获取当前的区域设置编码。
虽然文档没有指定如何编码。该函数位于 locale
模块中,因此我需要更改区域设置?有没有可靠的跨平台方法来设置UTF-8区域设置?它会影响除默认文本文件编码以外的任何其他内容吗?
或者区域设置更改是危险的(可以打破某些东西),我应该坚持自定义包装如: / p>
def uopen(* args,** kwargs):
return open(* args,encoding ='UTF-8 ',** kwargs)
语言环境或首选编码,因为;
- 它可能会影响代码的其他部分(或您使用的库);和
- 它不会清楚,您的代码依赖
打开
使用特定的编码。
而是使用一个简单的包装器:
from functools import partial
open_utf8 = partial(open,encoding ='UTF-8')
:
- 您可以为所有关键字参数指定默认值(如果需要)。
- 可以在调用该函数时覆盖默认值。
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)
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.
这篇关于有没有办法改变Python的open()默认文本编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!