Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 389
Krystian Cybulski Avatar asked Feb 06 '15 15:02

Krystian Cybulski


1 Answers

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'
>>> 
like image 95
SingleNegationElimination Avatar answered Oct 17 '22 08:10

SingleNegationElimination