【问题标题】:Change encoding while writing a file写入文件时更改编码
【发布时间】:2014-05-12 09:33:08
【问题描述】:

我正在写一个文件:

 with open("test_%s.tem" %i, "w") as f1:
 ....
 f1.close()

我想将编码转换为 UCS-2 little endian 格式。是否可以在 open() 或 close() 函数中执行此操作。任何想法都会有所帮助。

【问题讨论】:

标签: python


【解决方案1】:

Python 3,根据文档在:https://docs.python.org/3/library/functions.html#open
您可以使用 encoding 参数指定编码。

with open("test_%s.tem" %i, "w", encoding="utf16") as f1:

【讨论】:

  • 我使用的是 python 2.7。我尝试使用编解码器。但是它显示:UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 0: ordinal not in range(128)
  • ascii 值应介于 1128 之间。你正在尝试写239 (0xef)
【解决方案2】:

在 Python 2 上,您可以将 codecs.openencoding 参数一起使用。

如果您使用 Python 3,只需使用 openencoding 参数。

UCS-2 是 UTF-16 的子集,所以尽量使用'UTF-16' 作为参数值。

【讨论】:

    猜你喜欢
    • 2013-02-19
    • 1970-01-01
    • 2011-05-22
    • 2014-06-03
    • 2021-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多