Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python NamedTemporaryFile appears empty even after data is written

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()
like image 395
Matthew Lueder Avatar asked Sep 01 '17 16:09

Matthew Lueder


People also ask

What does TMP mean in Python?

Introduction. Temporary files, or "tempfiles", are mainly used to store intermediate information on disk for an application. These files are normally created for different purposes such as temporary backup or if the application is dealing with a large dataset bigger than the system's memory, etc.


1 Answers

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