Python file interface for strings

Is there a Python class that wraps the file interface (read, write, etc.) around a string? I mean something like stringstream classes in C ++.

I was thinking of using it to redirect print output to a string, e.g.

 sys.stdout = string_wrapper() print "foo", "bar", "baz" s = sys.stdout.to_string() #now s == "foo bar baz" 

EDIT: This is a duplicate. How do I transfer a string to a file in Python?

+4
source share
2 answers

Yes, there is StringIO:

 import StringIO import sys sys.stdout = StringIO.StringIO() print "foo", "bar", "baz" s = sys.stdout.getvalue() 
+12
source

For better performance, please note that you can also use cStringIO. But also note that this is not very portable for python 3.

+2
source

All Articles