Just pass encoding="utf-16"
when you open
your output file:
ch="Hello world, this a stackoverflow example"
with open("utf_16.txt", "w", encoding="utf-16") as f:
f.write(ch)
$ file utf_16.txt
utf_16.txt: Little-endian UTF-16 Unicode text, with no line terminators
$ hexdump -Cv utf_16.txt
00000000 ff fe 48 00 65 00 6c 00 6c 00 6f 00 20 00 77 00 |..H.e.l.l.o. .w.|
00000010 6f 00 72 00 6c 00 64 00 2c 00 20 00 74 00 68 00 |o.r.l.d.,.
.t.h.|
...
Note that utf-16
encoding includes a Byte-Order Mark (BOM). If you don't want this, include the endianness in the encoding name (e.g. utf-16le
):
ch="Hello world, this a stackoverflow example"
with open("utf_16.txt", "w", encoding="utf-16le") as f:
f.write(ch)
$ file utf_16.txt
utf_16.txt: data
$ hexdump -Cv utf_16.txt
00000000 48 00 65 00 6c 00 6c 00 6f 00 20 00 77 00 6f 00 |H.e.l.l.o. .w.o.|
00000010 72 00 6c 00 64 00 2c 00 20 00 74 00 68 00 69 00 |r.l.d.,. .t.h.i.|
...