无法获取有关在python中使用StringIO的read()的数据
使用Python2.7版本。 以下是我的示例代码。
import StringIO import sys buff = StringIO.StringIO() buff.write("hello") print buff.read() 在上面的程序中,read()没有返回任何值,因为getvalue()返回给我“hello”。 任何人都可以帮我解决这个问题吗? 我需要read(),因为我的下面的代码涉及读取“n”个字节。
 您需要将缓冲区位置重置为开始。 你可以通过做buff.seek(0)来做到这一点。 
每次读取或写入缓冲区时,位置都前进一位。 假设你从一个空的缓冲区开始。
 缓冲区值是"" ,缓冲区pos是0 。 你做buff.write("hello") 。 显然缓冲区值现在是hello 。 现在缓冲区的位置是5 。 当你打电话给read() ,没有任何过去的位置5可以阅读! 所以它返回一个空string。 
 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'