Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable SameFileError exception in shutil.copy

Tags:

python

shutil

I have the following code because sometimes these files will be the same and sometimes they won't.

import shutil
try:
   shutil.copy('filea','fileb')
   shutil.copy('filec','filed')
except shutil.SameFileError
   pass

The problem is that the second copy won't happen if the first copy has the same file.

Any suggestions on how to work around this? I don't see an argument in the shutil documentation that disables this check.

like image 839
Ray Salemi Avatar asked Jul 17 '19 20:07

Ray Salemi


People also ask

What is the use of shutil copy in Python?

shutil.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.

How to get the path to the file in error in shutil?

From reading the source, shutil.Error contains (src, dst, why) triplets. You can do something like: try: shutil.copytree (srcdir, dstdir) except shutil.Error, exc: errors = exc.args [0] for error in errors: src, dst, msg = error # Get the path to the file in Gold dir here from src shutil.copy2 (goldsrc, dst)

What is the difference between samefileerror and permissionerror?

If the source and destination represent the same file ‘SameFileError’ exception will be raised If the destination is is a directory then ‘IsADirectoryError’ exception will be raised If the destination is not writable ‘PermissionError’ exception will be raised


1 Answers

You can just separate the copy calls:

try:
   shutil.copy('filea','fileb')
except shutil.SameFileError:
   pass

try:
   shutil.copy('filec','filed')
except shutil.SameFileError:
   pass

Or put these four lines in a function.

like image 165
hko Avatar answered Oct 21 '22 13:10

hko