如何获取可用编码/解码编解码器的列表?



open的文档指出:

encoding is the name of the encoding used to decode or encode the
file. This should only be used in text mode.  The default encoding is
platform dependent, but any encoding supported by Python can be
passed.  See the codecs module for the list of supported encodings.

所以我import codecs然后理解我可以传入的内容作为要打开的encoding参数?

help(codecs)

同时列出 encode(( 的帮助。

以下文档页面还列出了支持的编码。 https://docs.python.org/3/library/codecs.html

不平凡 -

出于某种原因,无法列出来自 Python 解释器的编解码器。

编解码器模块允许使用

import codecs
codecs.lookup("codec_name")

但是编解码器注册表是解释器核心中的私有列表,即 不会仅向 Python 代码公开。

查找代码位于:https://github.com/python/cpython/blob/673c39331f844a80c465efd7cff88ac55c432bfb/Python/codecs.c#L100

尝试编写一个 C 简单函数以返回该内部列表的副本 很快发现它是解释器状态中的结构成员 保留供内部使用,不应被外部代码触及。

因此,您只能猜测编解码器名称,并使用上面的"查找"功能。

相关内容

最新更新