<tempfile, Python> ファイルからの読み出しはseek(0)がいる。

テンプファイルtempfileを使った時にちとはまったので、メモ。
tempfileを使って、一時的なファイルを作成し、その内容を読みだす場合、seek(0)しないといけん。

なんにもしないと、、

In [1]: import tempfile

In [6]: with tempfile.TemporaryFile(prefix='tempfile') as f:
   ...:     f.write('hogehoge'.encode('utf-8'))
   ...:     r = f.read()
   ...:     print(r)
   ...:     
b''

てな感じで返ってこない。

で、seek(0)すると、

In [7]: with tempfile.TemporaryFile(prefix='tempfile') as f:
   ...:     f.write('hogehoge'.encode('utf-8'))
   ...:     f.seek(0)
   ...:     r = f.read()
   ...:     print(r)
   ...:     
b'hogehoge'

やっほーう。 返ってきたよ!

ふと、、リードread()した結果は、バイトbyteっぽいから、デコードdecodeしてみた。

In [8]: with tempfile.TemporaryFile(prefix='tempfile') as f:
   ...:     f.write('hogehoge'.encode('utf-8'))
   ...:     f.seek(0)
   ...:     r = f.read()
   ...:     print(r.decode('utf-8'))
   ...:     
hogehoge

お世話になったところ。
tempfile – 一時的なファイルシステムリソースを作成する - Python Module of the Week