Python NamedTemporaryFile appears empty even after data is written

回眸只為那壹抹淺笑 提交于 2019-12-20 02:35:00

问题


In Python 2 it was easy to create a temporary file and access it. However with in Python 3 it seems that is no longer the case. I'm confused on how I can get to the file I create with tempfile.NamedTemporaryFile() so I can call a command on it.

For example:

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()

回答1:


The problem is with flushing. The file output is buffered for efficiency reasons, so you must flush it for the changes to be actually written to the file. Additionally, you should wrap this into a with context manager instead of explicit .close()

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


来源:https://stackoverflow.com/questions/46004774/python-namedtemporaryfile-appears-empty-even-after-data-is-written

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!