Relative seeks on string IO

Pierre Quentel pierre.quentel at
Tue Sep 6 09:18:16 CEST 2011


I am wondering why relative seeks fail on string IO in Python 3.2

Example :

    from io import StringIO
    txt = StringIO('Favourite Worst Nightmare') # no problem with absolute seek

but,1) # 2 characters from current position

raises "IOError: Can't do nonzero cur-relative seeks" (tested with
Python3.2.2 on WindowsXP)

A seek relative to the end of the string IO raises the same IOError

However, it is not difficult to simulate a class that performs
relative seeks on strings :

class FakeIO:

    def __init__(self,value):
        self.value = value
        self.pos = 0

    def read(self,nb=None):
        if nb is None:
            return self.value[self.pos:]
            return self.value[self.pos:self.pos+nb]

    def seek(self,offset,whence=0):
        if whence==0:
            self.pos = offset
        elif whence==1: # relative to current position
            self.pos += offset
        elif whence==2: # relative to end of string
            self.pos = len(self.value)+offset

txt = FakeIO('Favourite Worst Nightmare'),1),2)

Is there any reason why relative seeks on string IO are not allowed in
Python3.2, or is it a bug that could be fixed in a next version ?

- Pierre

More information about the Python-list mailing list