【问题标题】:Can't use readline() in StringIO [duplicate]不能在 StringIO 中使用 readline() [重复]
【发布时间】:2021-11-21 04:19:00
【问题描述】:

我想将一个字符串写入 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)

【问题讨论】:

    标签: python stringio


    【解决方案1】:

    您必须将(seek) stream position 更改为字节偏移量0。你也可以使用tell to get the current stream position

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

    【讨论】:

    • 谢谢,解决了!
    • 当你使用.write()方法写入流时,流位置会指示流的结束。要将流指示符位置重置为流的开头,可以直接将字符串读入StringIOfrom io import StringIO; temp = StringIO("This is a \n test sentence\n!");lines = [line for line in temp]; print(lines)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-24
    • 2018-10-28
    • 1970-01-01
    • 2012-08-08
    • 2013-05-13
    • 2019-02-02
    • 2022-10-23
    相关资源
    最近更新 更多