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?
Asked
Active
Viewed 8,713 times
20
-
2reset the pointer `s.seek(0)` – Padraic Cunningham Feb 06 '15 at 15:07
-
Why don't you just try it and see? – martineau Feb 06 '15 at 15:25
1 Answers
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