Reading from StringIO without resetting position

1.8k Views Asked by At

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.

2

There are 2 best solutions below

3
pylang On BEST ANSWER

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'
0
Michael Butscher On

You construct a StringIO object twice which is equal to opening the same file twice. Assign the object to e.g. fand call f.read() twice.