有没有办法改变 Python 的 open() 默认文本编码? [英] Is there a way to change Python's open() default text encoding?

查看:34
本文介绍了有没有办法改变 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() 默认文本编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆