Python NamedTemporaryFile appears empty even after data is written

后端 未结 1 1671
滥情空心
滥情空心 2021-01-12 02:46

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

相关标签:
1条回答
  • 2021-01-12 03:14

    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])
    
    0 讨论(0)
提交回复
热议问题