Skip to main content
 首页 » 编程设计

Python 使用 BOM 编写 UCS-2 Little Endian (utf-16-le) 文件

2025年05月04日7www_RR

<分区>

我有一个读取 utf-16-le 的 Unicode 文件的第 3 方应用程序。由于某种原因,它必须有 BOM,否则它不会读取文件。

我在编写这种编码的输出文件时遇到了很多困难,所以我想我会在这里记录我的解决方案,以供其他可能遇到相同问题的人使用。

import codecs 
 
mytext = "Help me" 
 
with open("c:\\temp\\myFile.txt", 'w') as f: 
    f.write(codecs.BOM_UTF16_LE) 
    f.write(mytext.encode('utf-16-le')) 

我被选择严重误导了‘correct answer’在以下线程中。

write('\ufeff') 

没有将所需的 BOM 标记写入文件(至少对使用 Python 2.7 的我来说没有) 你需要

write('\xff\xfe') 

我没有足够的声誉来发布,所以我发布自己的 Adding BOM (unicode signature) while saving file in python

我认为这与 Java 中的问题完全相同 Write text file in UCS-2 Little Endian, Java