views:

46

answers:

2

What is the best way to write the contents of a StringIO buf to a file ?

I currently do something like:

buf = StringIO()
fd = open ('file.xml', 'w')
# populate buf
fd.write (buf.getvalue ())

But then all of buf would be loaded in memory at the same time.. ?

A: 

Seek to the beginning, then read from it.

buf.seek(0)
t = buf.read(1048576)
while t:
  fd.write(t)
  t = buf.read(1048576)
Ignacio Vazquez-Abrams
magic number used: 1048576 reason: unknown
nosklo
+2  A: 

Use shutil.copyfileobj:

buf.seek(0)
shutil.copyfileobj(buf, fd)
Steven