我使用以下命令创建一个tmp文件:
from tempfile import mkstemp我尝试在这个文件中写道:
tmp_file = mkstemp()
file = open(tmp_file, 'w')
file.write('TEST\n')事实上,我关闭了文件,并做了适当的,但当我尝试猫的临时文件,它仍然empty..It看起来很基本,但我不知道为什么它不能工作,有任何解释吗?
发布于 2016-07-18 20:52:46
mkstemp()返回一个带有文件描述符和路径的元组。我认为问题在于你写错了方向。(您正在写入像'(5, "/some/path")'这样的路径。)您的代码应该如下所示:
from tempfile import mkstemp
fd, path = mkstemp()
# use a context manager to open the file at that path and close it again
with open(path, 'w') as f:
f.write('TEST\n')
# close the file descriptor
os.close(fd)发布于 2018-05-01 16:53:45
smarx的答案是通过指定path打开文件。但是,改为指定fd会更容易。在这种情况下,上下文管理器会自动关闭文件描述符:
from tempfile import mkstemp
fd, path = mkstemp()
# use a context manager to open (and close) file descriptor fd (which points to path)
with fdopen(fd, 'w') as f:
f.write('TEST\n')
# This causes the file descriptor to be closed automatically发布于 2019-03-27 15:41:59
这个示例使用os.fdopen打开Python文件描述符以编写很酷的东西,然后关闭它(在with上下文块的末尾)。其他非Python进程可以使用该文件。最后,该文件被删除。
import os
from tempfile import mkstemp
fd, path = mkstemp()
with os.fdopen(fd, 'w') as fp:
fp.write('cool stuff\n')
# Do something else with the file, e.g.
# os.system('cat ' + path)
# Delete the file
os.unlink(path)https://stackoverflow.com/questions/38436987
复制相似问题