Unable to Concatenate a file - destination kept getting overwritten
Peter Otten
__peter__ at web.de
Sat Apr 21 02:41:44 EDT 2012
Chris Angelico wrote:
> On Sat, Apr 21, 2012 at 11:03 AM, Foster Rilindo <rilindo at me.com> wrote:
>> Is this right way to concatenate a file or is there a better way?
>
> I'd be inclined to ignore shutil and simply open one file for reading,
> the other for appending, and manually transfer data from one to the
> other.
>
> open(disk1,"ab").write(open(disk2,"rb").read()) # untested
>
> This one-liner doesn't explicitly close its files, doesn't check for
> errors, etc, etc, but it should give you the idea of what's going on.
The advantage of copyfileobj() is that it limits memory consumption:
>>> print inspect.getsource(shutil.copyfileobj)
def copyfileobj(fsrc, fdst, length=16*1024):
"""copy data from file-like object fsrc to file-like object fdst"""
while 1:
buf = fsrc.read(length)
if not buf:
break
fdst.write(buf)
More information about the Python-list
mailing list