Python 写入 mkstemp() 文件

新手上路,请多包涵

我正在使用以下方法创建一个 tmp 文件:

 from tempfile import mkstemp

我正在尝试在此文件中写入:

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

事实上,我关闭了文件并正确执行,但是当我尝试 cat tmp 文件时,它仍然是空的。它看起来很基本,但我不知道为什么它不起作用,有什么解释吗?

原文由 Steeven_b 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 863
2 个回答

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)

原文由 user94559 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

 import os
from tempfile import mkstemp

fd, path = mkstemp()

# use a context manager to open (and close) file descriptor fd (which points to path)
with os.fdopen(fd, 'w') as f:
    f.write('TEST\n')

# This causes the file descriptor to be closed automatically

原文由 Guido van Steen 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题