Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 778
gauteh Avatar asked Jul 15 '10 07:07

gauteh


People also ask

How do I write a StringIO file?

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.

What is the use of StringIO in Python?

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.

How do you create a file like an object in Python?

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.


2 Answers

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).

like image 137
Steven Avatar answered Sep 23 '22 19:09

Steven


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()) 
like image 20
Demitri Avatar answered Sep 21 '22 19:09

Demitri