简体   繁体   中英

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

I have an array of text strings in 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.

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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