Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shutil.copy failure when the destination already exists and is read-only

Tags:

python

I am using shutil.copy to copy files from one location to another. If a file with the same name already exists in the destination location, it is normally ok and overwrites. However, if the destination is read-only, it throws a permission denied error.

What is the most elegant way to deal with this? Is there another shutil function that will deal with the permissions issue, or must I check the permissions on ever file I copy?

like image 580
coffee Avatar asked Aug 08 '11 15:08

coffee


2 Answers

smth like

import os
import shutil

def my_super_copy(what, where):
    try:
        shutil.copy(what, where)
    except IOError:
        os.chmod(where, 777) #?? still can raise exception
        shutil.copy(what, where)
like image 165
seriyPS Avatar answered Oct 02 '22 22:10

seriyPS


You don't have to check for permissions. Let the OS tell you there's a permission problem and then deal with it. I'm assuming that the PermissionDeniedError is the exception you're getting so your solution would look something like this.

try:
  shutil.copy(blah,blah,blah)
except PermissionDeniedError:
  <Code for whatever you want to do if there arent sufficient permissions>
like image 41
jjfine Avatar answered Oct 02 '22 23:10

jjfine