Unable to Concatenate a file - destination kept getting overwritten
Dave Angel
d at davea.name
Fri Apr 20 22:27:57 EDT 2012
On 04/20/2012 09:03 PM, Foster Rilindo wrote:
> I can't seem to concatenate.
>
> I got binary files here:
>
> yvaine:disk rilindo$ ls -lah
> total 61440
> drwxr-xr-x 4 rilindo staff 136B Apr 20 19:47 .
> drwxr-xr-x 10 rilindo staff 340B Apr 20 19:45 ..
> -rw-r--r-- 1 rilindo staff 20M Apr 20 20:00 disk1
> -rw-r--r-- 1 rilindo staff 10M Apr 20 19:47 disk2
>
> Based on the following code, I should be able to cat disk2 over to disk 1, resulting in a 30 Meg file:
>
>>>> import shutil
>>>> import os
>>>> disk1="/Users/rilindo/tmp/disk/disk1"
>>>> disk2="/Users/rilindo/tmp/disk/disk2"
>>>> destination = open(disk1,'wb')
>>>> shutil.copyfileobj(open(disk2,'rb'),destination)
>>>> destination.close()
> However, the result is that the destination gets overwritten:
>
> yvaine:disk rilindo$ ls -lah
> total 40960
> drwxr-xr-x 4 rilindo staff 136B Apr 20 19:47 .
> drwxr-xr-x 10 rilindo staff 340B Apr 20 19:45 ..
> -rw-r--r-- 1 rilindo staff 10M Apr 20 20:02 disk1
> -rw-r--r-- 1 rilindo staff 10M Apr 20 19:47 disk2
>
> Is this right way to concatenate a file or is there a better way?
>
> - Rilindo
I don't happen to be familiar with copyfileobj, but I can tell you that
the destination file is truncated even before the function is called.
destination = open(disk1,'wb')
will truncate the file before it returns the file object. You probably want 'a+b' rather than 'wb'
I still don't know if copyfileobj will do what you want, but you should be closer now.
-- DaveA
More information about the Python-list
mailing list