首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在mkstemp()文件中写入Python

在mkstemp()文件中写入Python
EN

Stack Overflow用户
提问于 2016-07-18 20:40:25
回答 4查看 22.5K关注 0票数 18

我使用以下命令创建一个tmp文件:

代码语言:javascript
复制
from tempfile import mkstemp

我尝试在这个文件中写道:

代码语言:javascript
复制
tmp_file = mkstemp()
file = open(tmp_file, 'w')
file.write('TEST\n')

事实上,我关闭了文件,并做了适当的,但当我尝试猫的临时文件,它仍然empty..It看起来很基本,但我不知道为什么它不能工作,有任何解释吗?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2016-07-18 20:52:46

mkstemp()返回一个带有文件描述符和路径的元组。我认为问题在于你写错了方向。(您正在写入像'(5, "/some/path")'这样的路径。)您的代码应该如下所示:

代码语言:javascript
复制
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)
票数 25
EN

Stack Overflow用户

发布于 2018-05-01 16:53:45

smarx的答案是通过指定path打开文件。但是,改为指定fd会更容易。在这种情况下,上下文管理器会自动关闭文件描述符:

代码语言:javascript
复制
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
票数 34
EN

Stack Overflow用户

发布于 2019-03-27 15:41:59

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

代码语言:javascript
复制
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)
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38436987

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档