I've written a python cgi app that lists image files in a directory then when the user clicks on a link it converts the image to a .jpg and displays it in a simple html page. I'm using tempfile.NamedTemporaryFile to create a temp file that the converter can write into, and the html code can then display. The problem is how to deal with removing the temp file. I would like to not clutter up the server with temp files, and no matter what i do, i can't seem to delete the file afterwards without causing a broken <img> link in the html page. I can turn delete=False on for the temp file and it works fine, but i would like to automatically remove the file after its been sent to the browser. Am i thinking about this in the wrong way? This is the first cgi app i've written and i'm not too familar with the practices.

Your image is not actually sent to the brower when your script ends. The browser downloads the html, finds a <img>-tag, and uses the url in the src-attribute to request the image from the server. So it's two separate requests.
What you could do, probably, is to intercept the request for the image, and delete it after it's sent to the server. Don't know how to do that, but it will depend heavily on your server-configuration (apache, iis etc)

That gives me another avenue to investigate, thanks.

Another option that doesn't involve messing with the server configuration, is to keep track of the last created temp-file. Save this in a file or database or something. Then, when you create a new temp-file, check if the last one exits and delete it if it's still there. Then you store the name of the new temporary file. This way you'll always have only one temporary file on the server.

That my friend is a good idea! I think that should work nicely. Sometimes you think to hard and look past simple ideas.