首页 > 解决方案 > 不能在 StringIO 中使用 readline()

问题描述

我想将字符串写入 StringIO() 对象,然后逐行读取;我尝试了两种方法,但都没有产生任何输出。我究竟做错了什么?

创建对象,写入它并检查它是否有效:

from io import StringIO
temp=StringIO()
temp.write("This is a \n test sentence\n!")
temp.getvalue() --> 'This is a \n test sentence\n!'

方法一:

for line in temp:
    print(line)

方法二:

test = True
while test:
    line = temp.readline()
    if not line:
         test=False
    else:
         print(line)

标签: pythonstringio

解决方案


您必须将( seek) 流位置更改为字节偏移量0。您还可以使用tell来获取当前流位置

>>> from io import StringIO
>>> temp = StringIO()
>>> temp.write("This is a \n test sentence\n!")
27
>>> temp.tell() # current stream position.
27
>>> temp.seek(0) # Change the stream position to the byte offset `0`
0
>>> for line in temp:
...     print(line)
...
This is a

 test sentence

!

推荐阅读