["python","file-io","temporary-files"]
How to use tempfile.NamedTemporaryFile() in Python

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 can't I do something like: os.system('start notepad.exe ' + tfName) at the end. I don't want to save the file permanently on my system. I just want the contents to be opened as a text in Notepad or similar application and delete the file when I close that application.
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. Edit: to answer some questions from the comments: As of the docs from 2 when using delete=False the file can be removed by using: tf.close() os.unlink(tf.name)