1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Python初心者】tempfileモジュールの基本と使い方まとめ

1
Posted at

一時ファイルや一時ディレクトリを自動で作ってくれる tempfile モジュールについて学びました。
今まであまり意識して使ったことがなかったのですが、使い方が分かってくると便利そうだったので記録としてまとめておきます。

ファイルを手動で削除する必要がないというのが、かなりありがたいです。

tempfileモジュールとは?

一時ファイルや一時ディレクトリを安全に作成・削除できる標準ライブラリです。
テストや一時的な処理に便利です。

import tempfile

NamedTemporaryFileの使い方

ファイル名がある一時ファイルを作るときに使います。

import tempfile

with tempfile.NamedTemporaryFile(mode='w+', delete=True) as tmp:
    tmp.write("hello")
    tmp.seek(0)
    print(tmp.read())  # => hello
  • mode='w+':読み書き可能
  • delete=True:閉じたときに削除
  • tmp.name:ファイルパスを確認可能

TemporaryFileの使い方

ファイル名が不要な一時ファイルを作りたいときに使います。
ファイル名がないので、他のプロセスからアクセスできません。

import tempfile

with tempfile.TemporaryFile(mode='w+t') as tmp:
    tmp.write("data")
    tmp.seek(0)
    print(tmp.read())  # => data
  • w+t:テキストモードで読み書き
  • 名前がないので tmp.name は使えません

SpooledTemporaryFileの使い方

データが少ないうちはメモリに保存し、一定サイズを超えると自動的に一時ファイルとしてディスクに書き出されます。

import tempfile

with tempfile.SpooledTemporaryFile(max_size=1000, mode='w+t') as tmp:
    tmp.write("memory first")
    tmp.seek(0)
    print(tmp.read())  # => memory first
  • max_size:このサイズを超えるとファイルに退避
  • パフォーマンスを意識した一時ファイル処理に便利

TemporaryDirectoryの使い方

一時的なディレクトリを作って、中にファイルなどを置くことができます。

import tempfile
import os

with tempfile.TemporaryDirectory() as tmpdir:
    print("一時ディレクトリ:", tmpdir)
    path = os.path.join(tmpdir, "test.txt")
    with open(path, "w") as f:
        f.write("temp")
    print(os.listdir(tmpdir))  # => ['test.txt']
  • with文を抜けるとディレクトリごと削除されます

その他の便利関数

import tempfile

print(tempfile.gettempdir())  # OSごとの一時ディレクトリパス
関数名 内容
gettempdir() 一時ファイルの標準保存先パスを返す
mkstemp() 一時ファイルを作成し、ファイルディスクリプタとパスを返す
mkdtemp() 一時ディレクトリを作成し、パスを返す(削除は自分で)

with文で使う理由

tempfile の多くは with 文で使うと、自動的にリソースをクリーンアップしてくれます。

with tempfile.NamedTemporaryFile() as tmp:
    tmp.write(b"data")
# ここで tmp は削除されている

明示的に os.remove() を書かなくてもいいので安全で便利です。

まとめ

今まで一時ファイルは自作して手動で消していたこともあったので、tempfile モジュールを使うことでとても楽になりそうです。
特に with 文と一緒に使うと、自動的に削除してくれるのが便利だと感じました。

次はこのモジュールをテストコードの中で使ってみたいです

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?