tempファイル
tempファイルの使い方 ▲
Python で tempファイル(一時ファイル) を使う方法について以下に記載する
lesson.py
import tempfile
# 一時ファイルを利用する(プログラム終了後に自動で破棄される)
with tempfile.TemporaryFile(mode='w+') as t:
t.write('hello')
t.seek(0)
print(t.read()) # hello
# 一時ファイルを名前を付けて利用する(プログラム終了後も消さずに残す)
with tempfile.NamedTemporaryFile(delete=False) as t:
print(t.name) # ~\AppData\Local\Temp\tmp78t8k999
with open(t.name, 'w+') as f:
f.write('test\n')
f.seek(0)
print(f.read()) # test
# 一時フォルダを利用する(プログラム終了後に自動で破棄される)
with tempfile.TemporaryDirectory() as td:
print(td) # ~\AppData\Local\Temp\tmpmp_u8by7
# 一時フォルダを利用する(プログラム終了後も消さずに残す)
temp_dir = tempfile.mkdtemp()
print(temp_dir) # ~\AppData\Local\Temp\tmp_mwdi6o9
目次