Failed to get data when using read () for StringIO in python

Using Python2.7. The following is sample code.

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

in the above program, read () returns me nothing, where getvalue () returns me "hello". Can someone help me in solving the problem? I need read () because my next code involves reading "n" bytes.

+52
python stringio
Apr 22 2018-12-12T00:
source share
2 answers

You need to reset the buffer position before starting. You can do this by running buff.seek(0) .

Each time you read or write to the buffer, the position advances by one. Say you start with an empty buffer.

Buffer value "" , pos buffer - 0 . You do buff.write("hello") . Obviously, the buffer value is now hello . However, the buffer position is now 5 . When you call read() , there is nothing previous to position 5 to read! Thus, it returns an empty string.

+75
Apr 22 '12 at 6:00
source share
 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' 

or

 In [5]: out = StringIO.StringIO() In [6]: out.write('use write') In [8]: out.seek(0) In [9]: out.read() Out[9]: 'use write' 
+9
Jul 28 '15 at 23:55
source share



All Articles