Search code examples
pythonstringio

Is it possible to rewind a python StringIO in-memory file?


Let's say I have a StringIO file-like object I just created from a string. I pass it to a function which expects files. This functions reads the entire file through the end. I want to now pass it to another function which expects a file-like object. Can I rewind it so that it can be read from the beginning? If not, what other approaches can I take to accomplish this that would be most pythonic?


Solution

  • certainly: most file-like objects in python that can possibly be rewound already support seek()

    >>> import StringIO
    >>> f = StringIO.StringIO("hello world")
    >>> f.read(6)
    'hello '
    >>> f.tell()
    6
    >>> f.seek(0)
    >>> f.tell()
    0
    >>> f.read()
    'hello world'
    >>>