in place input

Peter Otten __peter__ at web.de
Sun Oct 12 07:14:36 EDT 2003


andy at post.tau.ac.il wrote:

> i'm working on an python application with intensive i/o.
> 
> file.read() and its cousins all allocate and return a new string.
> 
> I want to know if there is a way in which I can provide the space on which
> the data is going to be put, in order to recycle memory, instead of
> allocating it each time again and again.

The following may do:

import array
file("tmp.txt", "w").write("x" * 5)
buf = array.array("c")
buf.fromstring("-" * 10)
print buf
file("tmp.txt", "r").readinto(buf)
print buf

However, file.readinto() has a frightening docstring:

>>> print file.readinto.__doc__
readinto() -> Undocumented.  Don't use this; it may go away.
>>>

Peter




More information about the Python-list mailing list