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.
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.
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)
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With