@kyanny's blog

My thoughts, my life. Views/opinions are my own.

Python: 一時ファイル(tempfile)を作る

tempfile モジュールを使う。

tempfile --- 一時ファイルやディレクトリの作成 — Python 3.9.4 ドキュメント

一時ファイルのパスが欲しい時は tempfile.TemporaryFile() ではなく tempfile.NamedTemporaryFile() を使う。パスは name 属性で得られる。デフォルトだと mode='w+b' でオープンされる。バイナリモードなので、文字列を書き込む時は b'string' を与える必要がある。テキストモードで開く場合は mode='w+t' オプションを与える。

gist.github.com