2021-08-03に投稿

Python 標準ライブラリ tempfile 一時ファイル・ディレクトリ作成

tempfileライブラリを使うと一時ファイルやディレクトリを作成できる。

自動的に破棄される一時ファイル

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

file_name = ''
with tempfile.TemporaryFile() as f:
    file_name = f.name
    f.write(b'abcd')
    f.seek(0)
    print(f.read())

print(pathlib.Path(file_name).exists()) # => False

名前付き一時ファイル

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

path = None
with tempfile.NamedTemporaryFile() as f:
    f.write(b'abcd')
    f.seek(0)
    print(f.read())
    path = f.name
    print(pathlib.Path(path).exists()) # => True

print(pathlib.Path(path).exists()) # => False
path = None
with tempfile.NamedTemporaryFile(delete=False) as f:
    f.write(b'abcd')
    f.seek(0)
    print(f.read())
    path = f.name
    print(pathlib.Path(path).exists()) # => True

print(pathlib.Path(path).exists()) # => True

メモリにスプールされる一時ファイル

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

path = None
with tempfile.SpooledTemporaryFile() as f:
    f.write(b'abcd')
    f.seek(0)
    print(f.read())

一時ディレクトリ

TemporaryDirectory(suffix=None, prefix=None, dir=None)

path = None
with tempfile.TemporaryDirectory() as td:
    path = td
    print(path) # => C:\Users\name\AppData\Local\Temp\tmpdfvdrov6
    f = pathlib.Path(path,'test.txt')
    f.touch()
    print(f.is_file()) # => True

print(pathlib.Path(path).exists()) # => False

競合しない一時ファイル作成

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

import os
try:
    hint, path = tempfile.mkstemp()
    f = pathlib.Path(path)
    f.write_text("あいうえお",encoding='utf8')
    print(f.read_text(encoding='utf8')) # => あいうえお
    print(f.exists()) # => True
finally:
    if f is not None and f.exists():
        os.close(hint)
        os.remove(path)

print(path) # => C:\Users\name\AppData\Local\Temp\tmp_lrv7som
print(f.exists()) # => False

競合しない一時ディレクトリ

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

import os
try:
    dir_path = tempfile.mkdtemp()
    d = pathlib.Path(dir_path)
    print(dir_path) # => C:\Users\name\AppData\Local\Temp\tmpdvbbwlcu
    print(d.exists()) # => True
finally:
    if d is not None and d.exists():
        d.rmdir()

print(d.exists()) # => False

一時ディレクトリ

tempfile.gettempdir() # => C:\Users\name\AppData\Local\Temp
Originally published at marusankakusikaku.jp
ツイッターでシェア
みんなに共有、忘れないようにメモ

maru3kaku4kaku

Pythonこつこつ学習中。よく忘れる。

Crieitは誰でも投稿できるサービスです。 是非記事の投稿をお願いします。どんな軽い内容でも投稿できます。

また、「こんな記事が読みたいけど見つからない!」という方は是非記事投稿リクエストボードへ!

有料記事を販売できるようになりました!

こじんまりと作業ログやメモ、進捗を書き残しておきたい方はボード機能をご利用ください。
ボードとは?

コメント