Is there a way to change Python#39;s open() default text encoding?(有没有办法改变 Python 的 open() 默认文本编码?)
问题描述
我可以更改默认的 open() (
io.open()
在 2.7 中) 跨平台的文本编码方式?
Can I change default open()
(io.open()
in 2.7) text encoding in a cross-platform way?
这样我就不需要每次都指定open(...,encoding='utf-8')
.
So that I didn't need to specify each time open(...,encoding='utf-8')
.
在文本模式下,如果未指定 encoding,则使用的编码取决于平台:调用 locale.getpreferredencoding(False)
以获取当前区域设置编码.>
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.
虽然文档没有指定如何设置首选编码.该函数在 locale
模块中,所以我需要更改语言环境?有没有可靠的跨平台方式来设置 UTF-8 语言环境?除了默认的文本文件编码之外,它会影响其他任何东西吗?
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;
- 它可能会影响您代码的其他部分(或您正在使用的库);和
- 不清楚您的代码是否依赖于使用特定编码的
open
.
相反,使用一个简单的包装器:
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).
这篇关于有没有办法改变 Python 的 open() 默认文本编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:有没有办法改变 Python 的 open() 默认文本编码?


基础教程推荐
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 筛选NumPy数组 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01