【问题标题】:Fail to get data on using read() of StringIO in python在 python 中使用 StringIO 的 read() 获取数据失败
【发布时间】:2012-05-03 04:22:12
【问题描述】:

使用Python2.7版本。下面是我的示例代码。

import StringIO
import sys

buff = StringIO.StringIO()
buff.write("hello")
print buff.read()

在上面的程序中,read() 没有返回任何内容,而 getvalue() 则返回“hello”。谁能帮我解决这个问题?我需要 read() 因为我的以下代码涉及读取“n”个字节。

【问题讨论】:

  • stringIO 中没有名为 read() 的函数
  • @ChasingDeath:是的。试试dir(StringIO.StringIO)
  • 是的,StringIO 为字符串创建了一个类似对象的文件,所以当然会有read()

标签: python stringio


【解决方案1】:

您需要将缓冲区位置重置为开头。你可以通过buff.seek(0) 来做到这一点。

每次读取或写入缓冲区时,位置都会提前一位。假设您从一个空缓冲区开始。

缓冲区值为"",缓冲区位置为0。 你做buff.write("hello")。显然缓冲区值现在是hello。但是,缓冲区位置现在是5。当您致电read() 时,位置 5 后面没有任何内容可供阅读!所以它返回一个空字符串。

【讨论】:

    【解决方案2】:
    In [38]: out_2 = StringIO.StringIO('not use write') # be initialized to an existing string by passing the string to the constructor
    
    In [39]: out_2.getvalue()
    Out[39]: 'not use write'
    
    In [40]: out_2.read()
    Out[40]: 'not use write'
    

    In [5]: out = StringIO.StringIO()
    
    In [6]: out.write('use write')
    
    In [8]: out.seek(0)
    
    In [9]: out.read()
    Out[9]: 'use write'
    

    【讨论】:

    • out.seek(0) 是我试图将泡菜转储到 StringIO 并上传到 s3 时所缺少的。一旦我推回到开头,我的 s3 对象就会被正确填充。
    猜你喜欢
    • 2018-11-15
    • 1970-01-01
    • 2014-12-16
    • 2019-06-10
    • 1970-01-01
    • 1970-01-01
    • 2022-07-25
    • 2014-11-17
    • 1970-01-01
    相关资源
    最近更新 更多