20

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?

Krystian Cybulski
  • 10,789
  • 12
  • 67
  • 98

1 Answers1

35

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'
>>> 
SingleNegationElimination
  • 151,563
  • 33
  • 264
  • 304