Python 写入 mkstemp() 文件

标签 python mkstemp

我正在使用 :

创建一个 tmp 文件
from tempfile import mkstemp

我正在尝试在这个文件中写入:

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

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

最佳答案

smarx 的答案通过指定路径 打开文件。但是,指定 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

关于Python 写入 mkstemp() 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38436987/

相关文章:

python - 从之前保存的 hdf5 文件中加载部分模型权重

c - 获取由 mkstemp() 创建的文件名

python - tempfile.mkstemp 权限设置

c++ - win32 的 mkstemp() 实现

c++ - 如何为临时文件创建 std::ofstream?

python - 无法处理通过 scikit-image 在 OpenCV 中转换的图像

Python:尝试/排除整个模块

python - 基本上我正在尝试做一个 python-sql 连接器程序,但目前我遇到了这个错误

Python ImportError 无法导入 urandom 自 Ubuntu 12.04 升级