あなたが「WB」としてあなたの出力ファイルを開くと、それはバイトストリームではなく、Unicodeの引数を受け付けます。
s = 'слово'
with open('data.txt','wb') as f:
f.write(s.encode('unicode_escape'))
f.write(b'\n') # add a line feed
これは、あなたがやりたいようだ:
$ cat data.txt
\u0441\u043b\u043e\u0432\u043e
、それUnicodeをテキストストリームに書き込むときに起こるデコードと変換の両方を回避します。
@ J.F.Sebastianの提案に従って、encode( 'unicode_escape')を使用するように更新されました。 timeitが、それはかなり速くエンコード( 'ASCII'、 'backslashreplace' バック)よりであることを報告し
%:
In [18]: f = open('data.txt', 'wb')
In [19]: %timeit f.write(s.encode('unicode_escape'))
The slowest run took 224.43 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 1.55 µs per loop
In [20]: %timeit f.write(s.encode('ascii','backslashreplace'))
The slowest run took 9.13 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 2.37 µs per loop
In [21]: f.close()
不思議なことに、エンコードのためにはtimeitからラグ( 'unicode_escape')たくさん長いですループごとの時間がより速いにもかかわらず、encode( 'ascii'、 'backslashreplace')よりも速いので、あなたの環境で両方をテストしてください。
どのpythonバージョンですか? –
@ Ni。私はPython 3を使用しています – reynoldsnlp
あなたがこれを頻繁にやっていることがわかったら、あなたのためにそれを行うための非常に短い関数を書いてください。説得力のある理由がない限り、効率を心配しないでください。 –