Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python file interface for strings [duplicate]

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

I was thinking of using it to redirect the output of print into a string, like this

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

EDIT: This is a duplicate of How do I wrap a string in a file in Python?

like image 266
CAdaker Avatar asked Dec 10 '22 22:12

CAdaker


1 Answers

Yes, there is StringIO:

import StringIO
import sys


sys.stdout = StringIO.StringIO()
print "foo", "bar", "baz"
s = sys.stdout.getvalue()
like image 143
Peter Hoffmann Avatar answered Dec 28 '22 00:12

Peter Hoffmann