convert string to input stream

Jeremy Jones zanesdad at bellsouth.net
Tue Aug 31 12:47:33 EDT 2004


Titus Barik wrote:

>Hi,
>
>I've used Google quite a bit in an attempt to find an answer to this
>question, but have found no leads, possibly because I'm not sure I'm
>wording my question properly. So I thought I'd try here.
>
>Basically I have a function that accepts an input file stream as an
>argument:
>
>	handle = open(SOME_FILE)
>	my_function(handle)
>
>But occasionally, I end up with a string ("Hello world") that I need to
>convert to a stream in order to pass it into this function. Perhaps
>something like:
>
>	fake_handle = convert_to_handle("Hello world!")
>  
>
What you want is StringIO:
http://www.python.org/doc/current/lib/module-StringIO.html
or cStringIO:
http://www.python.org/doc/current/lib/module-cStringIO.html

I'll leave usage between you and the pydocs (unless, of course, you try 
it and have some problems with it).

>so that it appears to this function to be a file handle. I've seen
>functions in other languages that will take strings and convert them to
>streams via IO Memory Buffers and such, but can't seem to find anything in
>Python; or at least I don't know where to look.
>
>One solution that I didn't like was to do the following:
>
>	1. Open a temporary file.
>	2. Write the string to that file.
>	3. Read it back.
>  
>
Yeah - that's a nasty answer.  You don't wanna go there.

>Any suggestions are appreciated.
>
>Regards,
>
>
>  
>




More information about the Python-list mailing list