how to use tempfile.NamedTemporaryFile() in python

Manoj picture Manoj · Oct 13, 2010 · Viewed 77.9k times · Source

I want to use tempfile.NamedTemporaryFile() to write some contents into it and then open that file. I have written following code:

tf = tempfile.NamedTemporaryFile()
tfName = tf.name
tf.seek(0)
tf.write(contents)
tf.flush()

but I am unable to open this file and see its contents in notepad or similar application. Is there any way to achieve this? Why cant I do something like:

os.system('start notepad.exe ' + tfName)

at the end

Answer

Dave Webb picture Dave Webb · Oct 13, 2010

This could be one of two reasons:

Firstly, by default the temporary file is deleted as soon as it is closed. To fix this use:

tf = tempfile.NamedTemporaryFile(delete=False)

and then delete the file manually once you've finished viewing it in the other application.

Alternatively, it could be that because the file is still open in Python Windows won't let you open it using another application.