在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()
答案 0 :(得分:7)
问题在于潮红。出于效率原因,文件输出是缓冲的,因此您必须flush
它才能将更改实际写入文件。此外,您应该将其包装到with
上下文管理器中,而不是显式.close()
with tempfile.NamedTemporaryFile() as temp:
temp.write(someData)
temp.flush()
subprocess.call(['cat', temp.name])