我想为python中的文本文件生成Unicode UTF-16

问题描述 投票:0回答:1

就像在图片中一样,我在文件中有一个普通文本,我想用unicode编写这样的文件enter image description here

我正在使用此代码,但是它无法完成工作,它只是按原样编写文本,而我确实需要显示utf-16编码

with open(localOutputPath,'r') as infile:
        data = infile.read()
        #print(data)

    with open(localUtf16Path, 'w', encoding="utf-16") as outfile:
        outfile.write(data)
python character-encoding utf-16
1个回答
0
投票

完全没用:

==> type .\SO\62111029.py
import io
localOutputPath = r'd:\bat\62111029input.txt'
localUtf16Path  = r'd:\bat\62111029output.txt'
data = []
with io.open(localOutputPath, mode="r", encoding="utf-8") as infile:
    with io.open(localUtf16Path, mode="w", encoding="utf-8") as outfile:
        for line in infile:
            data = ''.join(['u\\' + '{:04x}'.format(ord(letter))
                for letter in line.rstrip('\n')]).replace('u\\0020',' ')
            outfile.write(data + '\n')
==> 2>NUL del 62111029output.txt

==> type 62111029input.txt
September 1, 1939
1 Σεπτεμβρίου 1939
1 сентября 1939
1. září 1939
==> .\SO\62111029.py

==> type 62111029output.txt
u\0053u\0065u\0070u\0074u\0065u\006du\0062u\0065u\0072 u\0031u\002c u\0031u\0039u\0033u\0039
u\0031 u\03a3u\03b5u\03c0u\03c4u\03b5u\03bcu\03b2u\03c1u\03afu\03bfu\03c5 u\0031u\0039u\0033u\0039
u\0031 u\0441u\0435u\043du\0442u\044fu\0431u\0440u\044f u\0031u\0039u\0033u\0039
u\0031u\002e u\007au\00e1u\0159u\00ed u\0031u\0039u\0033u\0039
© www.soinside.com 2019 - 2024. All rights reserved.