Python using cStringIO with foreach loop

北城以北 提交于 2019-12-11 05:58:16

问题


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.


回答1:


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)



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/40551529/python-using-cstringio-with-foreach-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!