Search code examples
pythonstringiocstringio

Reading from StringIO without resetting position


I have a test code with the following:

with open('master.log') as f:
    print(f.read(8))
    print(f.read(8))

This prints as:

>> pi@raspberrypi:~/workspace/Program $ sudo python test.py
>> 12/29/20
>> 17 12:52

This has different prints as you can see. However, when I do this:

import cStringIO

stream= "1234567890"
print(cStringIO.StringIO(stream).read(8))
print(cStringIO.StringIO(stream).read(8))

When I run this, I get this following output:

>> pi@raspberrypi:~/workspace/Program $ sudo python test.py
>> 12345678
>> 12345678

In this case, it outputs the same values (the seeker doesn't advance).

I need to make it so cStringIO (or a similar solution) reads strings the same way as files. Without resetting the position every read I mean.


Solution

  • As @Michael Butscher and other's have eluded to, you need to make an instance of the stream.

    >>> #import io                                      # python 3
    >>> import cStringIO as io                          # python 2 
    >>> stream = "1234567890"
    >>> f = io.StringIO(stream)
    >>> f.read(8)
    '12345678'
    >>> f.read(8)
    '90'