pythonpython-2.7cstringio

Python using cStringIO with foreach loop


I want to iterate over lines cStringIO object, however it does not seem to work with foreach loop. To be more precise the behavior is as if the collection was empty. What am I doing wrong?

example:

Python 2.7.12 (default, Aug 29 2016, 16:51:45)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import cStringIO
>>> s = cStringIO.StringIO()
>>> import os
>>> s.write("Hello" + os.linesep + "World" + os.linesep)
>>> s.getvalue()
'Hello\nWorld\n'
>>> for line in s :
...     print line
...
>>>

Thank you.


Solution

  • cStringIO.StringIO returns either cStringIO.InputType object i.e input stream if provided a string else or cStringIO.OutputType object i.e output stream.

    In [13]: sio = cStringIO.StringIO()
    
    In [14]: sio??
    Type:        StringO
    String form: <cStringIO.StringO object at 0x7f63d418f538>
    Docstring:   Simple type for output to strings.
    
    In [15]: isinstance(sio, cStringIO.OutputType)
    Out[15]: True
    
    In [16]: sio = cStringIO.StringIO("dsaknml")
    
    In [17]: sio??
    Type:        StringI
    String form: <cStringIO.StringI object at 0x7f63d4218580>
    Docstring:   Simple type for treating strings as input file streams
    
    In [18]: isinstance(sio, cStringIO.InputType)
    Out[18]: True
    

    So you can either do read operations or write operations but not both. a simple solution to do read operations on a cStringIO.OutputType object is by converting it into the value by getvalue() method.

    If you try do both operations then either of them gets ignored silently.

    cStringIO.OutputType.getvalue(c_string_io_object)