1

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.

jlanik
  • 859
  • 5
  • 12

3 Answers3

2

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)
eightnoteight
  • 234
  • 2
  • 11
1

Try using the string split method:

for line in s.getvalue().split('\n'): print line
...
Hello
World

Or as suggested, if you are always splitting on a new line:

for line in s.getvalue().splitlines(): print line
LMc
  • 12,577
  • 3
  • 31
  • 43
  • 1
    prefer using `str.splitlines()` rather than `str.split('\n')` just because of readability and making your code more pythonic – Stam Kaly Nov 11 '16 at 16:02
0

You can read the contents from an open file handle after writing, but you first have to use the seek(0) method to move the pointer back to the start. This will work for either cStringIO or a real file:

import cStringIO
s = cStringIO.StringIO()
s.write("Hello\nWorld\n") # Python automatically converts '\n' as needed 
s.getvalue()
# 'Hello\nWorld\n'
s.seek(0)  # move pointer to start of file
for line in s :
    print line.strip()
# Hello
# World
Matthias Fripp
  • 17,670
  • 5
  • 28
  • 45