使用Python2.7版本。以下是我的示例代码。
import StringIO
import sys
buff = StringIO.StringIO()
buff.write("hello")
print buff.read()
在上面的程序中,read()没有返回任何内容,因为getvalue()返回“hello”。任何人都可以帮我解决问题吗?我需要read()因为我的下面的代码涉及读“n”字节。
答案 0 :(得分:87)
您需要将缓冲区位置重置为开头。您可以通过buff.seek(0)
执行此操作。
每次读取或写入缓冲区时,位置都会提前一个。假设你从空缓冲区开始。
缓冲区值为""
,缓冲区pos为0
。
你做buff.write("hello")
。显然缓冲区值现在为hello
。但是,缓冲区位置现在为5
。当你拨打read()
时,没有任何东西可以通过位置5来阅读!所以它返回一个空字符串。
答案 1 :(得分:15)
oracle.rules.rl.exceptions.UndefinedException: The symbol "mypackage.MyUtil" is undefined.
at line 22 column 14 in /Ruleset(main)
or
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'