3👍
✅
You can save it to a StringIO
object instead of a file (use the cStringIO
module, if possible):
from StringIO import StringIO
fake_file = StringIO()
thing.save(fake_file) # Acts like a file handle
contents = fake_file.getvalue()
fake_file.close()
Or if you like context managers:
import contextlib
from StringIO import StringIO
with contextlib.closing(StringIO()) as handle:
thing.save(handle)
contents = handle.getvalue()
Source:stackexchange.com