3

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.

Helder Esteves
  • 451
  • 4
  • 13
  • 1
    You're creating a *whole new* StringIO object every time you run `cStringIO.StringIO(stream)`. If you used the same one twice, the position would be retained. – Charles Duffy Dec 29 '17 at 02:11

2 Answers2

1

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.

Michael Butscher
  • 10,028
  • 4
  • 24
  • 25
1

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'
pylang
  • 40,867
  • 14
  • 129
  • 121