Python 標準ライブラリ tempfile 一時ファイル・ディレクトリ作成
      
      
      Publish date: 2021-08-03
      
        
      
    
    
      
    
    
    
    
      
    
    
    
    
    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()) # => Falsepath = 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