即使在写入数据后,Python NamedTemporaryFile 仍显示为空

标签 python python-3.x temporary-files

在 Python 2 中,创建临时文件并访问它很容易。然而,在 Python 3 中,情况似乎不再如此。我对如何获取使用 tempfile.NamedTemporaryFile() 创建的文件感到困惑,以便我可以对其调用命令。

例如:

temp = tempfile.NamedTemporaryFile()
temp.write(someData)
subprocess.call(['cat', temp.name]) # Doesn't print anything out as if file was empty (would work in python 2)
subprocess.call(['cat', "%s%s" % (tempfile.gettempdir(), temp.name])) # Doesn't print anything out as if file was empty
temp.close()

最佳答案

问题在于冲洗。出于效率原因,文件输出被缓冲,因此您必须 flush 它才能将更改实际写入文件。此外,您应该将其包装到 with 上下文管理器中,而不是显式 .close()

with tempfile.NamedTemporaryFile() as temp:
    temp.write(someData)
    temp.flush()
    subprocess.call(['cat', temp.name])

关于即使在写入数据后,Python NamedTemporaryFile 仍显示为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46004774/

相关文章:

Python Beautifulsoup : file. write(str) 方法获取 TypeError : write() argument must be str, 不是 BeautifulSoup

python - Django 没有名为 utils 的模块

python - python 中的单个 var 赋值和多个 var 赋值之间有什么不同的行为吗?

python - 如何在 Python 中的 Windows 上创建一个命名的临时文件?

javascript - 如何在 nodejs 中的多次运行之间保留临时文件?

python - Django:为什么当我在 django 中通过 popen 使用 Ghostscript 时,会出现 "file not found"错误

python - Pandas - 如果行包含相同的值,如何匹配行

python - 在字符串中查找最重复(不是最常见)序列的算法(又名串联重复)

python - 操作列时如何使用 pandas 数据帧处理 "divide by zero"?

Python 的 tempfile.mkstemp() 返回一个整数而不是文件句柄?