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() 默认文本编码?
基础教程推荐
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
