Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would shutil.copy() raise a permission exception when cp doesn't?

People also ask

What is the difference between Shutil copy () and Shutil copy2 () functions?

The shutil. copy2() method is identical to shutil. copy() except that copy2() attempts to preserve file metadata as well.

How do I use Shutil copy in Python?

copy() method in Python is used to copy the content of source file to destination file or directory. It also preserves the file's permission mode but other metadata of the file like the file's creation and modification times is not preserved.

Is Shutil copy Atomic?

No, it seems to just loop, reading and writing 16KB at a time. For an atomic copy operation, you should copy the file to a different location on the same filesystem, and then os. rename() it to the desired location (which is guaranteed to be atomic on Linux).


The operation that is failing is chmod, not the copy itself:

  File "/usr/lib/python2.7/shutil.py", line 91, in copymode
    os.chmod(dst, mode)
OSError: [Errno 1] Operation not permitted: 'bin/styles/blacktie/images/ajax-loader-000000-e3e3e3.gif'

This indicates that the file already exists and is owned by another user.

shutil.copy is specified to copy permission bits. If you only want the file contents to be copied, use shutil.copyfile(src, dst), or shutil.copyfile(src, os.path.join(dst, os.path.basename(src))) if dst is a directory.

A function that works with dst either a file or a directory and does not copy permission bits:

def copy(src, dst):
    if os.path.isdir(dst):
        dst = os.path.join(dst, os.path.basename(src))
    shutil.copyfile(src, dst)

This form worked for me:

shutil.copy('/src_path/filename','/dest_path/filename')