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 5 years have passed since last update.

tempfile

Posted at
1
import tempfile

with tempfile.TemporaryFile(mode='w+') as t:
    t.write('Hello')
    t.seek(0)
    print(t.read())

with tempfile.NamedTemporaryFile(delete=False) as t:
    print(t.name)
    with open(t.name, 'w+') as f:
        f.write('test\n')
        f.seek(0)
        print(f.read())
1の実行結果
Hello
/tmp/tmpahd0kr2●●●
test

print(t.read())で書き込んだHelloが出力される。
これは一時ファイルなので削除される。

NamedTemporaryFile(delete=False)とする事で、
削除されずファイルを残す事ができる。

次に一時ファイルではなく、
一時的なディレクトリをつくる。

2
with tempfile.TemporaryDirectory() as td:
    print(td)

temp_dir = tempfile.mkdtemp()
print(temp_dir)
2の実行結果
/tmp/tmp9bq6_n●●
/tmp/tmpiybl8b●●

tdは一時的なディレクトリ。
temp_dirはtempfile.mkdtemp()とする事で、
削除されずディレクトリを残す事ができる。

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?