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)
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)
from tempfile import mkstemp
fd, path = mkstemp()
# use a context manager to open (and close) file descriptor fd (which points to path)
with open(fd, 'w') as f:
f.write('TEST\n')
# This causes the file descriptor to be closed automatically
mkstemp()
返回具有文件描述符和路径的元组。我认为问题是你的写作方向不对。(您正在写入类似'(5, "/some/path")'
的路径。)您的代码应该如下所示:这个例子用^{} 打开Python文件描述符来编写很酷的东西,然后关闭它(在
with
上下文块的末尾)。其他非Python进程可以使用该文件。最后,文件被删除。smarx的应答通过指定
path
打开文件。但是,更容易指定fd
。在这种情况下,上下文管理器会自动关闭文件描述符:相关问题 更多 >
编程相关推荐