今日は、Pythonのtempfileモジュールの使い方を紹介します。
このモジュールは、一時ファイルを保存したいときに非常に便利です。
アプリケーションの観点からは、一時的なデータを保存する必要があるため、これらのファイルは非常に有用であることがわかります。
Python は tempfile モジュールを提供してくれています。
さっそく始めてみましょう。
Python の tempfile モジュール
このモジュールは標準ライブラリ(Python 3.x)の一部なので、pipを使って何かをインストールする必要はありません。
import tempfile
|
これから、一時ファイルやディレクトリを作成する方法を見ていきます。
一時ファイルおよびディレクトリの作成
tempfileモジュールはTemporaryFile()` メソッドを提供し、一時ファイルを作成します。
このファイルは一時的なものなので、他のプログラムはこのファイルに直接アクセスすることはできません。
一般的な安全対策として、Pythonは閉じた後に作成された一時ファイルを自動的に削除します。
たとえ開いたままであっても、プログラムが完了した後、この一時的なデータは削除されます。
では、簡単な例を見てみましょう。
import tempfile
# We create a temporary file using tempfile.TemporaryFile()temp = tempfile.TemporaryFile()
# Temporary files are stored heretemp_dir = tempfile.gettempdir()
print(f"Temporary files are stored at: {temp_dir}")
print(f"Created a tempfile object: {temp}")
print(f"The name of the temp file is: {temp.name}")
# This will clean up the file and delete it automaticallytemp.close() |
結果は以下の通りです。
Temporary files are stored at: /tmp
Created a tempfile object: <_io.BufferedRandom name=3>
The name of the temp file is: 3
|
では、tempfile.gettempdir() を使って、すべての一時ファイルが格納されているディレクトリを取得し、このファイルを探してみましょう。
プログラムを実行した後、temp_dir (私の場合 – Linux では /tmp) に移動すると、新しく作成されたファイル 3 がそこにないことがわかります。
ls: cannot access '3': No such file or directory
|
これは、Pythonがこれらの一時ファイルを閉じた後、自動的に削除していることを証明しています。
さて、一時ファイルを作るのと同じように、 tempfile.TemporaryDirectory() 関数を使って一時ディレクトリを作ることができます。
tempfile.TemporaryDirectory(suffix=None, prefix=None, dir=None)
|
ディレクトリ名はランダムなので、オプションで suffix や prefix を指定して、プログラムの一部として識別できるようにすることができます。
また、関連するコードが完了した後にディレクトリを安全に削除するために、コンテキストマネージャーを使用して安全にラップすることができます!
import tempfile
with tempfile.TemporaryDirectory() as tmpdir: # The context manager will automatically delete this directory after this section
print(f"Created a temporary directory: {tmpdir}")
print("The temporary directory is deleted")
|
結果は以下の通りです。
Created a temporary directory: /tmp/tmpa3udfwu6
The temporary directory is deleted
|
繰り返しますが、これを確認するために、関連するディレクトリのパスに移動してみると、存在しないことがわかります!
1. 一時ファイルからの読み出しと書き込み
ファイルからの読み込み、書き込みと同様に、一時ファイルからも同じような関数呼び出しが可能です。
import tempfile
with tempfile.TemporaryFile() as fp: name = fp.name
fp.write(b'Hello from AskPython!') # Write a byte string using fp.write()
fp.seek(0) # Go to the start of the file
content = fp.read() # Read the contents using fp.read()
print(f"Content of file {name}: {content}")
print("File is now deleted")
|
では、出力を見てみましょう。
結果は以下の通りです。
Content of file 3: b'Hello from AskPython!'
File is now deleted
|
確かに、一時ファイルからの読み書きが簡単にできるようになりました。
2. 名前付きテンポラリファイルの作成
ある状況下では、名前付きテンポラリファイルは、他のスクリプトやプロセスからファイルを見えるようにして、まだ閉じていない間にアクセスできるようにするのに便利かもしれません。
この場合、tempfile.NamedTemporaryFile()が役に立ちます。
これは、通常の一時ファイルを作成するのと同じ構文です。
import tempfile
# We create a named temporary file using tempfile.NamedTemporaryFile()temp = tempfile.NamedTemporaryFile(suffix='_temp', prefix='askpython_')
print(f"Created a Named Temporary File {temp.name}")
temp.close()print("File is deleted")
|
結果は以下の通りです。
Created a Named Temporary File /tmp/askpython_r2m23q4x_temp
File is deleted
|
ここでは、プレフィックスが askpython_ で、サフィックスが _temp の名前付きテンポラリファイルが作成されます。
ここでも、クローズされた後、自動的に削除されます。
まとめ
今回は、Pythonのtempfileモジュールを使って、一時ファイルやディレクトリを扱う方法について学びました。