import os import tempfile with tempfile.TemporaryDirectory() as dirpath: with open(os.path.join(dirpath,'file1'),mode='w',encoding='utf-8') as f1, \ open(os.path.join(dirpath, 'file2'), mode='w', encoding='utf-8') as f2: print(dirpath) f1.write("file1") f2.write("file2")
という一時ディレクトリを作ってその一時ディレクトリにファイルを作って書き込むコードがあります。
with tempfile.TemporaryDirectory() as dirpath:
でわざわざwith構文を使って一時ディレクトリの変数dirpathを作っている理由がわかりません。
dirpath = tempfile.TemporaryDirectory() with open(os.path.join(dirpath,'file1'),mode='w',encoding='utf-8') as f1, \
でいいのではないかと思います。なぜwith構文を使っているのでしょうか?このwith構文を抜けた時、一時ディレクトリを消す役割をwith構文は持っているのでしょうか?
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2017/11/30 08:30
退会済みユーザー
2017/11/30 08:31
2017/11/30 08:33
退会済みユーザー
2017/11/30 08:42
2017/11/30 08:45
退会済みユーザー
2017/11/30 08:52
2017/11/30 09:04 編集
退会済みユーザー
2017/11/30 10:42