无法在python中使用StringIO的read()获取数据

raj*_*raj 64 python stringio

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

import StringIO
import sys

buff = StringIO.StringIO()
buff.write("hello")
print buff.read()
Run Code Online (Sandbox Code Playgroud)

在上面的程序中,read()不返回任何内容,因为getvalue()返回"hello".任何人都可以帮我解决问题吗?我需要read(),因为我的以下代码涉及读取"n"字节.

Joe*_*ett 91

您需要将缓冲区位置重置为开头.你可以这样做buff.seek(0).

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

缓冲区值是""缓冲区pos 0.你呢buff.write("hello").显然缓冲区值现在是hello.然而,缓冲位置现在是5.当你打电话时read(),没有任何东西可以通过位置5阅读!所以它返回一个空字符串.


Vin*_*Lee 19

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'
Run Code Online (Sandbox Code Playgroud)

要么

In [5]: out = StringIO.StringIO()

In [6]: out.write('use write')

In [8]: out.seek(0)

In [9]: out.read()
Out[9]: 'use write'
Run Code Online (Sandbox Code Playgroud)