在 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/