gauteh gauteh - 3 months ago 16
Python Question

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

What is the best way to write the contents of a

StringIO
buffer to a file ?

I currently do something like:

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


But then the whole buffer would be loaded in memory at the same time.. ?

Answer

Use shutil.copyfileobj:

with open ('file.xml', 'w') as fd:
  buf.seek (0)
  shutil.copyfileobj (buf, fd)
Comments