views:

44

answers:

2

I'm using xlwt in python to create a Excel spreadsheet. You could interchange this for almost anything else that generates a file; it's what I want to do with the file that's important.

from xlwt import *

w = Workbook()
#... do something
w.save('filename.xls')

I want to I have two use cases for the file: I stream it out to the user's browser or I attach it to an email. In both cases the file only needs to exist the duration of the web request that generates it.

What I'm getting at, the reason for starting this thread is saving to a real file on the filesystem has its own hurdles (stopping overwriting, cleaning up the file once done). Is there somewhere I could "save" it where it lives only in memory and only for the duration of the request?

+2  A: 

cStringIO

(or mmap if it should be mutable)

katrielalex
Great stuff. I had thought about something like this but assumed (incorrectly) that xlwt would only take a filename and not an object.
Oli
Polymorphism ftw!
katrielalex
Hmmm ... if you mutate the resulting file image, please don't report problems trying to read it.
John Machin
+1  A: 

Generalising the answer, as you suggested: If the "anything else that generates a file" won't accept a file-like object as well as a filepath, then you can reduce the hassle by using tempfile.NamedTemporaryFile

John Machin