Copying data between file-like objects
Thomas Lotze
thomas at thomas-lotze.de
Wed Feb 16 03:36:25 EST 2005
Fredrik Lundh wrote:
> copyfileobj copies from the current location, and write leaves the file
> pointer at the end of the file. a s.seek(0) before the copy fixes that.
Damn, this cannot be read from the documentation, and combined with the
fact that there's no length parameter for a portion to copy either, I
thought copying would mean copying all.
> getvalue() returns the contents of the f2 file as a string, and f1 will
> use that string as the buffer. there's no extra copying.
Oh, good to know. Then StringIO(f2.getvalue()) or StringIO(f2.read())
would be the way to go.
>> Because I want to manipulate a copy of the data and be able to compare
>> it to the original afterwards.
>
> why not just use a plain string (or a list of strings)? your focus on
> StringIO sounds like a leftover from some C library you've been using in
> an earlier life ;-)
Because the data can be a lot, and modifying long strings means a lot of
slicing and copying partial strings around, if I understand right.
Modifying a StringIO buffer is possible in-place. Plus, it's easier to
teach an algorithm that works on a StringIO to use a file instead, so I
may be able to avoid reading stuff into memory altogether in certain
places without worrying about special cases.
> use a plain string and slicing. (if you insist on using StringIO, use
> seek and read)
OK.
--
Thomas
More information about the Python-list
mailing list