Python

pythonで一時ファイル、一時ディレクトリ(tempfile)

pythonで一時ファイルを使うにはtempfileを使う。

p.py
import tempfile
import os


def main():
    with tempfile.NamedTemporaryFile() as fp:
        filename = fp.name
    if not os.path.isfile(filename):
        print(filename + ' is not exists')

    with tempfile.TemporaryDirectory() as td:
        dirname = td
    if not os.path.isdir(dirname):
        print(dirname + ' is not exists')


if __name__ == '__main__':
    main()
    exit(0)


"""
/tmp/tmpvdjzflod is not exists
/tmp/tmpwwtl1bun is not exists
"""

ただし、3.2以上でないとTemporaryDirectoryは使えないので注意

/tmp/tmp3OJjCi is not exists
Traceback (most recent call last):
  File "/home/ymko/tmp/testtest/p.py", line 21, in <module>
    main()
  File "/home/ymko/tmp/testtest/p.py", line 11, in main
    with tempfile.TemporaryDirectory() as td:
AttributeError: 'module' object has no attribute 'TemporaryDirectory'

Process finished with exit code 1

NamedTemporaryFileとTemporaryFileどちらを使えばいいのか悩みどころだが互換性を考えるとNamedTemporaryFileが良いようだ。
O_TMPFILEを使いたい場合はTemporaryFileを呼ぶ必要がある。

tempfile.py
def NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None,
                       newline=None, suffix=None, prefix=None,
                       dir=None, delete=True):
...
if _os.name != 'posix' or _os.sys.platform == 'cygwin':
    # On non-POSIX and Cygwin systems, assume that we cannot unlink a file
    # while it is open.
    TemporaryFile = NamedTemporaryFile

else:
    # Is the O_TMPFILE flag available and does it work?
    # The flag is set to False if os.open(dir, os.O_TMPFILE) raises an
    # IsADirectoryError exception
    _O_TMPFILE_WORKS = hasattr(_os, 'O_TMPFILE')

    def TemporaryFile(mode='w+b', buffering=-1, encoding=None,
                      newline=None, suffix=None, prefix=None,
                      dir=None):

11.6. tempfile — 一時ファイルやディレクトリの作成 — Python 3.6.3 ドキュメント
Community Blog - ファイルオープンと新フラグ