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

PythonFile IoStringio

Python Problem Overview


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 buf.getvalue() would make a copy of the contents?

Python Solutions


Solution 1 - Python

Use shutil.copyfileobj:

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

or shutil.copyfileobj(buf, fd, -1) to copy from a file object without using chunks of limited size (used to avoid uncontrolled memory consumption).

Solution 2 - Python

Python 3:

from io import StringIO
...
with open('file.xml', mode='w') as f:
    print(buf.getvalue(), file=f)

Python 2.x:

from StringIO import StringIO
...
with open('file.xml', mode='w') as f:
    f.write(buf.getvalue())

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiongautehView Question on Stackoverflow
Solution 1 - PythonStevenView Answer on Stackoverflow
Solution 2 - PythonDemitriView Answer on Stackoverflow