我正在使用 :
创建一个 tmp 文件from tempfile import mkstemp
我正在尝试在这个文件中写入:
tmp_file = mkstemp()
file = open(tmp_file, 'w')
file.write('TEST\n')
确实我关闭了文件并正确执行了但是当我尝试 cat tmp 文件时,它仍然是空的..它看起来很基本但我不知道为什么它不起作用,有什么解释吗?
最佳答案
smarx 的答案通过指定路径
打开文件。但是,指定 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
关于Python 写入 mkstemp() 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38436987/