简体   繁体   English

Python将行写入UCS-2 LE BOM编码的文本文件

[英]Python write lines to a UCS-2 LE BOM encoded text file

I have an array of text strings in Python 3.7. 我在Python 3.7中有一组文本字符串。

Now I want to write them all to a text file. 现在,我想将它们全部写入文本文件。 The problem is, that textfile has to be in encoding UCS-2 LE BOM (thats what it says about its encoding in Notepad++), otherwise the file won't work in further processing. 问题在于,该文本文件必须以UCS-2 LE BOM编码(这就是它在Notepad ++中的编码说明),否则该文件将无法继续处理。

How do I write the text strings to the file in that encoding while the strings staying readable? 如何在文本字符串保持可读性的同时将文本字符串写入文件中?

    with open(textpath, "w", encoding='utf-16-le') as f:
    for line in newlines:
        f.write(line)

This does not work because it generates gibberish text... 这不起作用,因为它会产生乱码...

Try writing an explicit BOM: 尝试编写一个明确的BOM:

with open(textpath, "w", encoding='utf-16-le') as f:
    f.write('\ufeff')
    for line in newlines:
        f.write(line)
        # Perhaps you also need to add a newline after each line?
        f.write('\n')

Obviously revert the last addition if your lines already have newlines. 如果您的行已经有换行符,显然可以还原最后添加的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM