Python は mkstemp() ファイルに書き込みます 質問する

Python は mkstemp() ファイルに書き込みます 質問する

以下を使用して tmp ファイルを作成しています:

from tempfile import mkstemp

このファイルに書き込もうとしています:

tmp_file = mkstemp()
file = open(tmp_file, 'w')
file.write('TEST\n')

確かにファイルを閉じて適切に実行しましたが、tmp ファイルを cat しようとすると、まだ空のままです。基本的なように見えますが、なぜ機能しないのかわかりません。説明はありますか?

ベストアンサー1

smarx の回答では、 を指定してファイルを開きますpath。ただし、代わりに を指定する方が簡単ですfd。その場合、コンテキスト マネージャーはファイル記述子を自動的に閉じます。

import os
from tempfile import mkstemp

fd, path = mkstemp()

# use a context manager to open (and close) file descriptor fd (which points to path)
with os.fdopen(fd, 'w') as f:
    f.write('TEST\n')

# This causes the file descriptor to be closed automatically

おすすめ記事