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

I use shutil.copy to copy files from one place to another. If a file with the same name already exists at the destination location, it is usually normal and overwritten. However, if the destination is read-only, it throws an error that is prohibited by permission.

What is the most elegant way to handle this? Is there any other shutil function that will deal with the permissions issue, or should I check permissions for the file I am copying ever?

+6
source share
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) 
+4
source

You do not need to check permissions. Let the OS inform you of a resolution problem, and then handle it. I assume PermissionDeniedError is the exception you get, so your solution will look something like this.

 try: shutil.copy(blah,blah,blah) except PermissionDeniedError: <Code for whatever you want to do if there arent sufficient permissions> 
+1
source

Source: https://habr.com/ru/post/894550/


All Articles