views:

54

answers:

2

Hi, 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

A: 

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.

Dave Webb
A: 

Recipe 10.6 in The Python Cookbook details exactly how to do this. Full credit to Larry Price and Peter Cogolo, the authors of that recipe, for this answer.

Rafe Kettler