Python在mkstemp()fi中写入

2024-10-01 09:25:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个tmp文件,使用:

from tempfile import mkstemp

我试图在这个文件中写入:

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

确实,我关闭了这个文件并做了正确的操作,但是当我尝试对tmp文件进行分类时,它仍然是空的……它看起来很基本,但是我不知道为什么它不起作用,有什么解释吗?


Tags: 文件fromtestimport分类opentempfiletmp
3条回答

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)

这个例子用^{}打开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)

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

相关问题 更多 >