0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

tempfile

Posted at

#ファイルの入出力のテストに使います。

import tempfile

#withを閉じるとファイルは削除されます
with tempfile.TemporaryFile(mode='w+') as t:
    t.write('hello')
    t.seek(0)
    print(t.read())

#withを閉じた後もファイルは残ります
with tempfile.NamedTemporaryFile(delete=False, mode='w+') as t:
    print(t.name)
    t.write('test\n')
    t.seek(0)
    print(t.read())

#withを閉じるとディレクトリは削除されます
with tempfile.TemporaryDirectory() as td:
    print(td)

#ディレクトリは削除されません
temp_dir = tempfile.mkdtemp()
print(temp_dir)
hello
/var/folders/0j/3nls1w512cdc4h2fr4543lw40000gn/T/tmplb079t65
test

/var/folders/0j/3nls1w512cdc4h2fr4543lw40000gn/T/tmp_tnjm74h
/var/folders/0j/3nls1w512cdc4h2fr4543lw40000gn/T/tmp1b75osd0
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?