If you want to create temporary files in Python, there is a module called tempfile in the standard Python libraries. If you want to run other programs to work with the file, use tempfile.mkstemp () to create the files and os.fdopen () to access the file descriptors that mkstemp () provides.
By the way, you say that you use commands from the Python program? You will almost certainly use the subprocess module.
So you can pretty fun write code that looks like this:
import subprocess import tempfile import os (fd, filename) = tempfile.mkstemp() try: tfile = os.fdopen(fd, "w") tfile.write("Hello, world!\n") tfile.close() subprocess.Popen(["/bin/cat", filename]).wait() finally: os.remove(filename)
By running this, you should find that the cat worked fine, but the temporary file was deleted in the finally block. Keep in mind that you need to delete the temporary file that mkstemp () returns on its own - the library does not know when you are done with it!
(Edit: I suggested that NamedTemporaryFile did exactly what you need, but it may not be so convenient - the file is deleted immediately when the temp file object is closed, and other processes open the file before it is closed, it will not work on some platforms, in particular Windows. Sorry, not on my part.)
Richard Barrell Jun 02 '10 at 9:13
source share