Fail to get data on using read() of StringIO in python

后端 未结 2 729
余生分开走
余生分开走 2021-01-31 06:42

Using Python2.7 version. Below is my sample code.

import StringIO
import sys

buff = StringIO.StringIO()
buff.write(\"hello\")
print buff.read()
<
2条回答
  •  走了就别回头了
    2021-01-31 07:37

    You need to reset the buffer position to the beginning. You can do this by doing buff.seek(0).

    Every time you read or write to the buffer, the position is advanced by one. Say you start with an empty buffer.

    The buffer value is "", the buffer pos is 0. You do buff.write("hello"). Obviously the buffer value is now hello. The buffer position, however, is now 5. When you call read(), there is nothing past position 5 to read! So it returns an empty string.

提交回复
热议问题