Python在mkstemp()文件中写入

Ste*_*n_b 6 python mkstemp

我正在创建一个tmp文件:

from tempfile import mkstemp
Run Code Online (Sandbox Code Playgroud)

我想写这个文件:

tmp_file = mkstemp()
file = open(tmp_file, 'w')
file.write('TEST\n')
Run Code Online (Sandbox Code Playgroud)

事实上,我关闭文件并正确执行但是当我尝试捕获tmp文件时,它仍然是空的..它看起来基本但我不知道为什么它不起作用,任何解释?

Gui*_*een 13

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 open(fd, 'w') as f:
    f.write('TEST\n')

# This causes the file descriptor to be closed automatically
Run Code Online (Sandbox Code Playgroud)

  • 我认为这种解决方案更好,但是您需要使用`os.fdopen()`而不是`open()`。(至少在python 2.7中,我不确定python 3) (3认同)

use*_*559 12

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)
Run Code Online (Sandbox Code Playgroud)


Mik*_*e T 8

此示例打开 Python 文件描述符来os.fdopen编写很酷的东西,然后关闭它(在上下文块的末尾with)。其他非 Python 进程可以使用该文件。最后,该文件被删除。

import os
from tempfile import mkstemp

fd, path = mkstemp(text=True)

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.remove(path)
Run Code Online (Sandbox Code Playgroud)