即使写入数据,Python NamedTemporaryFile也显示为空

Mat*_*der 3 python temporary-files python-3.x

在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()
Run Code Online (Sandbox Code Playgroud)

Ant*_*ala 7

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

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