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 – Write String to Text FileOpen the text file in write mode using open() function. The function returns a file object. Call write() function on the file object, and pass the string to write() function as argument. Once all the writing is done, close the file using close() function.
The StringIO module is an in-memory file-like object. This object can be used as input or output to the most function that would expect a standard file object. When the StringIO object is created it is initialized by passing a string to the constructor. If no string is passed the StringIO will start empty.
To create a file object in Python use the built-in functions, such as open() and os. popen() . IOError exception is raised when a file object is misused, or file operation fails for an I/O-related reason. For example, when you try to write to a file when a file is opened in read-only mode.
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).
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With