Python将cStringIO与foreach循环结合使用 [英] Python using cStringIO with foreach loop

查看:118
本文介绍了Python将cStringIO与foreach循环结合使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想遍历cStringIO对象行,但是它似乎不适用于foreach循环.更确切地说,行为就像集合是空的.我在做什么错了?

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?

示例:

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
...
>>>

谢谢.

推荐答案

cStringIO.StringIO返回cStringIO.InputType对象即输入流(如果提供了字符串),或者返回cStringIO.OutputType对象即输出流.

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

因此您可以执行读操作或写操作,但不能两者都进行.一个对cStringIO.OutputType对象进行读取操作的简单解决方案是通过getvalue()方法将其转换为值.

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)

这篇关于Python将cStringIO与foreach循环结合使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆