1

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

例子:

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

谢谢你。

4

3 回答 3

2

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

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() 方法将其转换为值。

如果您尝试执行这两种操作,那么它们中的任何一个都会被静默忽略。

cStringIO.OutputType.getvalue(c_string_io_object)
于 2016-11-11T17:39:57.873 回答
1

尝试使用字符串split方法:

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

或者按照建议,如果您总是在新行上拆分:

for line in s.getvalue().splitlines(): print line
于 2016-11-11T15:56:37.637 回答
0

您可以在写入后从打开的文件句柄中读取内容,但您首先必须使用该seek(0)方法将指针移回开始处。这适用于 cStringIO 或真实文件:

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
于 2018-02-07T22:08:28.090 回答