tempfile --- 一時ファイルやディレクトリの作成

ソースコード: Lib/tempfile.py


This module creates temporary files and directories. It works on all supported platforms. TemporaryFile, NamedTemporaryFile, TemporaryDirectory, and SpooledTemporaryFile are high-level interfaces which provide automatic cleanup and can be used as context managers. mkstemp() and mkdtemp() are lower-level functions which require manual cleanup.

ユーザが呼び出し可能な全ての関数とコンストラクタは追加の引数を受け取ります。 その引数によって一時ファイルやディレクトリの場所と名前を直接操作することが出来ます。 このモジュールに使用されるファイル名はランダムな文字を含みます。そのためファイルは共有された一時ディレクトリに安全に作成されます。 後方互換性を保つために引数の順序は若干奇妙です。 分かりやすさのためにキーワード引数を使用してください。

このモジュールではユーザが呼び出し可能な以下の項目を定義しています:

tempfile.TemporaryFile(mode='w+b', buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, *, errors=None)

一時的な記憶領域として使うことの出来る file-like object を返します。 ファイルは mkstemp() と同じルールにより安全に作成されます。 オブジェクトは閉じられる (オブジェクトのガベージコレクションによる暗黙的なものも含みます) とすぐに破壊されます。 Unix では、そのファイルのディレクトリエントリは全く作成されないか、ファイル作成後すぐに削除されます。 これは他のプラットフォームではサポートされません。 よって、この関数で作成された一時ファイルがファイルシステムで可視な名前を持つかどうかをコードで当てにすべきではありません。

The resulting object can be used as a context manager (see 使用例). On completion of the context or destruction of the file object the temporary file will be removed from the filesystem.

作成されたファイルを閉じることなく読み書きできるように、 mode 引数のデフォルトは 'w+b' です。 保存されるデータに関わらず全てのプラットフォーム上で一貫して動作するようにバイナリモードが使用されます。 bufferingencodingerrorsnewline は、 open() に対する引数として解釈されます。

dirprefixsuffix 引数の意味とデフォルトは mkstemp() のものと同じです。

返されたオブジェクトは、POSIXプラットフォームでは本物のファイルオブジェクトです。 それ以外のプラットフォームでは、file 属性が下層の本物のファイルであるファイル様オブジェクトです。

The os.O_TMPFILE flag is used if it is available and works (Linux-specific, requires Linux kernel 3.11 or later).

On platforms that are neither Posix nor Cygwin, TemporaryFile is an alias for NamedTemporaryFile.

引数 fullpath を指定して 監査イベント tempfile.mkstemp を送出します。

バージョン 3.5 で変更: The os.O_TMPFILE flag is now used if available.

バージョン 3.8 で変更: errors 引数が追加されました。

tempfile.NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, delete=True, *, errors=None, delete_on_close=True)

This function operates exactly as TemporaryFile() does, except the following differences:

  • This function returns a file that is guaranteed to have a visible name in the file system.

  • To manage the named file, it extends the parameters of TemporaryFile() with delete and delete_on_close parameters that determine whether and how the named file should be automatically deleted.

The returned object is always a file-like object whose file attribute is the underlying true file object. This file-like object can be used in a with statement, just like a normal file. The name of the temporary file can be retrieved from the name attribute of the returned file-like object. On Unix, unlike with the TemporaryFile(), the directory entry does not get unlinked immediately after the file creation.

If delete is true (the default) and delete_on_close is true (the default), the file is deleted as soon as it is closed. If delete is true and delete_on_close is false, the file is deleted on context manager exit only, or else when the file-like object is finalized. Deletion is not always guaranteed in this case (see object.__del__()). If delete is false, the value of delete_on_close is ignored.

Therefore to use the name of the temporary file to reopen the file after closing it, either make sure not to delete the file upon closure (set the delete parameter to be false) or, in case the temporary file is created in a with statement, set the delete_on_close parameter to be false. The latter approach is recommended as it provides assistance in automatic cleaning of the temporary file upon the context manager exit.

Opening the temporary file again by its name while it is still open works as follows:

  • On POSIX the file can always be opened again.

  • On Windows, make sure that at least one of the following conditions are fulfilled:

    • delete is false

    • additional open shares delete access (e.g. by calling os.open() with the flag O_TEMPORARY)

    • delete is true but delete_on_close is false. Note, that in this case the additional opens that do not share delete access (e.g. created via builtin open()) must be closed before exiting the context manager, else the os.unlink() call on context manager exit will fail with a PermissionError.

On Windows, if delete_on_close is false, and the file is created in a directory for which the user lacks delete access, then the os.unlink() call on exit of the context manager will fail with a PermissionError. This cannot happen when delete_on_close is true because delete access is requested by the open, which fails immediately if the requested access is not granted.

On POSIX (only), a process that is terminated abruptly with SIGKILL cannot automatically delete any NamedTemporaryFiles it created.

引数 fullpath を指定して 監査イベント tempfile.mkstemp を送出します。

バージョン 3.8 で変更: errors 引数が追加されました。

バージョン 3.12 で変更: Added delete_on_close parameter.

class tempfile.SpooledTemporaryFile(max_size=0, mode='w+b', buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, *, errors=None)

This class operates exactly as TemporaryFile() does, except that data is spooled in memory until the file size exceeds max_size, or until the file's fileno() method is called, at which point the contents are written to disk and operation proceeds as with TemporaryFile().

rollover()

The resulting file has one additional method, rollover(), which causes the file to roll over to an on-disk file regardless of its size.

The returned object is a file-like object whose _file attribute is either an io.BytesIO or io.TextIOWrapper object (depending on whether binary or text mode was specified) or a true file object, depending on whether rollover() has been called. This file-like object can be used in a with statement, just like a normal file.

バージョン 3.3 で変更: the truncate method now accepts a size argument.

バージョン 3.8 で変更: errors 引数が追加されました。

バージョン 3.11 で変更: Fully implements the io.BufferedIOBase and io.TextIOBase abstract base classes (depending on whether binary or text mode was specified).

class tempfile.TemporaryDirectory(suffix=None, prefix=None, dir=None, ignore_cleanup_errors=False, *, delete=True)

This class securely creates a temporary directory using the same rules as mkdtemp(). The resulting object can be used as a context manager (see 使用例). On completion of the context or destruction of the temporary directory object, the newly created temporary directory and all its contents are removed from the filesystem.

name

The directory name can be retrieved from the name attribute of the returned object. When the returned object is used as a context manager, the name will be assigned to the target of the as clause in the with statement, if there is one.

cleanup()

The directory can be explicitly cleaned up by calling the cleanup() method. If ignore_cleanup_errors is true, any unhandled exceptions during explicit or implicit cleanup (such as a PermissionError removing open files on Windows) will be ignored, and the remaining removable items deleted on a "best-effort" basis. Otherwise, errors will be raised in whatever context cleanup occurs (the cleanup() call, exiting the context manager, when the object is garbage-collected or during interpreter shutdown).

The delete parameter can be used to disable cleanup of the directory tree upon exiting the context. While it may seem unusual for a context manager to disable the action taken when exiting the context, it can be useful during debugging or when you need your cleanup behavior to be conditional based on other logic.

引数 fullpath を指定して 監査イベント tempfile.mkdtemp を送出します。

バージョン 3.2 で追加.

バージョン 3.10 で変更: ignore_cleanup_errors 引数が追加されました。

バージョン 3.12 で変更: Added the delete parameter.

tempfile.mkstemp(suffix=None, prefix=None, dir=None, text=False)

可能な限り最も安全な手段で一時ファイルを生成します。 プラットフォームが os.open()os.O_EXCL フラグを正しく実装している限り、ファイルの作成で競合が起こることはありません。 作成したユーザのユーザ ID からのみファイルを読み書き出来ます。 プラットフォームがファイルが実行可能かどうかを示す許可ビットを使用している場合、ファイルは誰からも実行不可です。 このファイルのファイル記述子は子プロセスに継承されません。

TemporaryFile() と違って、 mkstemp() のユーザは用済みになった時に一時ファイルを削除しなければなりません。

suffixNone でない場合、ファイル名はその接尾辞で終わります。 そうでない場合、接尾辞はありません。 mkstemp() はファイル名と接尾辞の間にドットを追加しません。 必要であれば suffix の先頭につけてください。

prefixNone でない場合、ファイル名はその接頭辞で始まります。 そうでない場合、デフォルトの接頭辞が使われます。 必要に応じ、デフォルトは gettempprefix() または gettempprefixb() の返り値です。

dirNone でない場合、ファイルはそのディレクトリ下に作成されます。 None の場合、デフォルトのディレクトリが使われます。デフォルトのディレクトリはプラットフォームに依存するリストから選ばれますが、アプリケーションのユーザは TMPDIRTEMP、または TMP 環境変数を設定することでディレクトリの場所を管理することができます。そのため、生成されるファイル名が、os.popen() で外部コマンドにクォーティング無しで渡すことができるなどといった、扱いやすい性質を持つ保証はありません。

suffixprefixdir のいずれかが None でない場合、それらは同じ型でなければなりません。 bytes の場合、返された名前は str でなはく bytes です。 他の挙動はデフォルトで返り値を bytes に強制的にしたい場合は suffix=b'' を渡してください。

text に真を指定した場合は、ファイルはテキストモードで開かれます。そうでない場合(デフォルト)は、ファイルはバイナリモードで開かれます。

mkstemp() は開かれたファイルを扱うための OS レベルのハンドル (os.open() が返すものと同じ) とファイルの絶対パス名が順番に並んだタプルを返します。

引数 fullpath を指定して 監査イベント tempfile.mkstemp を送出します。

バージョン 3.5 で変更: suffixprefixdir は bytes の返り値を得るために bytes で渡すことが出来ます。 それ以前は str のみ許されていました。 適切なデフォルト値を使用するよう、suffixprefixNone を受け入れ、デフォルトにするようになりました。

バージョン 3.6 で変更: dir パラメタが path-like object を受け付けるようになりました。

tempfile.mkdtemp(suffix=None, prefix=None, dir=None)

可能な限り安全な方法で一時ディレクトリを作成します。 ディレクトリの生成で競合は発生しません。 ディレクトリを作成したユーザ ID だけが、このディレクトリに対して内容を読み出したり、書き込んだり、検索したりすることができます。

mkdtemp() のユーザは用済みになった時に一時ディレクトリとその中身を削除しなければなりません。

prefix, suffix, dir 引数は mkstemp() 関数のものと同じです。

mkdtemp() は新たに生成されたディレクトリの絶対パス名を返します。

引数 fullpath を指定して 監査イベント tempfile.mkdtemp を送出します。

バージョン 3.5 で変更: suffixprefixdir は bytes の返り値を得るために bytes で渡すことが出来ます。 それ以前は str のみ許されていました。 適切なデフォルト値を使用するよう、suffixprefixNone を受け入れ、デフォルトにするようになりました。

バージョン 3.6 で変更: dir パラメタが path-like object を受け付けるようになりました。

バージョン 3.12 で変更: mkdtemp() now always returns an absolute path, even if dir is relative.

tempfile.gettempdir()

一時ファイルに用いられるディレクトリの名前を返します。 これはモジュール内の全ての関数の dir 引数のデフォルト値を定義します。

Python は呼び出したユーザがファイルを作ることの出来るディレクトリを検索するのに標準的なリストを使用します。 そのリストは:

  1. 環境変数 TMPDIR で与えられているディレクトリ名。

  2. 環境変数 TEMP で与えられているディレクトリ名。

  3. 環境変数 TMP で与えられているディレクトリ名。

  4. プラットフォーム依存の場所:

    • Windows ではディレクトリ C:\TEMPC:\TMP\TEMP 、および \TMP の順。

    • その他の全てのプラットフォームでは、 /tmp/var/tmp 、および /usr/tmp の順。

  5. 最後の手段として、現在の作業ディレクトリ。

この検索の結果はキャッシュされます。以下の tempdir の記述を参照してください。

バージョン 3.10 で変更: Always returns a str. Previously it would return any tempdir value regardless of type so long as it was not None.

tempfile.gettempdirb()

gettempdir() と同じですが返り値は bytesです。

バージョン 3.5 で追加.

tempfile.gettempprefix()

一時ファイルを生成する際に使われるファイル名の接頭辞を返します。 これにはディレクトリ部は含まれません。

tempfile.gettempprefixb()

gettempprefix() と同じですが返り値は bytes です。

バージョン 3.5 で追加.

The module uses a global variable to store the name of the directory used for temporary files returned by gettempdir(). It can be set directly to override the selection process, but this is discouraged. All functions in this module take a dir argument which can be used to specify the directory. This is the recommended approach that does not surprise other unsuspecting code by changing global API behavior.

tempfile.tempdir

When set to a value other than None, this variable defines the default value for the dir argument to the functions defined in this module, including its type, bytes or str. It cannot be a path-like object.

tempdir が (デフォルトの) None の場合、 gettempprefix() を除く上記のいずれかの関数を呼び出す際は常に gettempdir() で述べられているアルゴリズムによって初期化されます。

注釈

Beware that if you set tempdir to a bytes value, there is a nasty side effect: The global default return type of mkstemp() and mkdtemp() changes to bytes when no explicit prefix, suffix, or dir arguments of type str are supplied. Please do not write code expecting or depending on this. This awkward behavior is maintained for compatibility with the historical implementation.

使用例

tempfile モジュールの典型的な使用法のいくつかの例を挙げます:

>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile() as fp:
...     fp.write(b'Hello world!')
...     fp.seek(0)
...     fp.read()
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary file using a context manager
# close the file, use the name to open the file again
>>> with tempfile.NamedTemporaryFile(delete_on_close=False) as fp:
...     fp.write(b'Hello world!')
...     fp.close()
... # the file is closed, but not removed
... # open the file again by using its name
...     with open(fp.name, mode='rb') as f:
...         f.read()
b'Hello world!'
>>>
# file is now removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory() as tmpdirname:
...     print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed

非推奨の関数と変数

一時ファイルを作成する歴史的な手法は、まず mktemp() 関数でファイル名を作り、その名前を使ってファイルを作成するというものでした。 残念ながらこの方法は安全ではありません。 なぜなら、mktemp() の呼び出しと最初のプロセスが続いてファイル作成を試みる間に、異なるプロセスがその名前でファイルを同時に作成するかもしれないからです。 解決策は二つのステップを同時に行い、ファイルをすぐに作成するというものです。 この方法は mkstemp() や上述している他の関数で使用されています。

tempfile.mktemp(suffix='', prefix='tmp', dir=None)

バージョン 2.3 で非推奨: 代わりに mkstemp() を使って下さい。

呼び出し時には存在しなかった、ファイルの絶対パス名を返します。 prefixsuffixdir 引数は mkstemp() のものと似ていますが、bytes のファイル名、suffix=None、そして prefix=None がサポートされていない点で異なります。

警告

この関数を使うとプログラムのセキュリティホールになる可能性があります。この関数がファイル名を返した後、あなたがそのファイル名を使って次に何かをしようとする段階に至る前に、誰か他の人間があなたを出し抜くことができてしまいます。 mktemp() の利用は、 NamedTemporaryFile()delete=False 引数を渡すことで、簡単に置き換えることができます:

>>> f = NamedTemporaryFile(delete=False)
>>> f.name
'/tmp/tmptjujjt'
>>> f.write(b"Hello World!\n")
13
>>> f.close()
>>> os.unlink(f.name)
>>> os.path.exists(f.name)
False