-1

for example i read from the file 1:

ch="Hello world, this a stackoverflow example"

i write in file 2 the unicode UTF-16, the output must be like that:

output="\u0048\u0065\u006c\u006c\u006f \u0077\u006f\u0072\u006c\u0064\u002c \u0074\u0068\u0069\u0073 \u0061 \u0073\u0074\u0061\u0063\u006b\u006f\u0076\u0065\u0072 \u0066\u006c\u006f\u0077 \u0065\u0078\u0061\u006d\u0070\u006c\u0065"

i found how to convert or read, but not how to transform

Moun
  • 325
  • 2
  • 16
  • Please clarify if you want the `ch` string encoded in bytes as UTF-16, or the *literal characters* backslash, `u`, `0`, `0`, `4`, `8`, etc. in the file. – Mark Tolonen Jun 02 '20 at 06:11

1 Answers1

1

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.|
...
Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328