1

I'm currently trying to create a python script. One of the steps is that it shall create a copy of a folder, including subfolders, and checks beforehand if the folder already exists. If yes, then it should delete the folder first. Unfortunately, the folder is quite big and I'm running on network errors most of the time. Therefore, the task stops in the middle and I have to manually restart the script. How can I implement a retry. If it fails to delete or copy a file in the folder, it should retry for a certain amount.

The current function definition is quite straight forward like this:

def copy_directory(root_directory, target_directory):
    import shutil
    import os
    if os.path.isdir(target_directory) == True:
        shutil.rmtree(target_directory)
        shutil.copytree(root_directory, target_directory)
    else:
        shutil.copytree(root_directory, target_directory)

copy_directory(path_folderA, path_folderAcopy)

After searching I'm thinking to implement sth. like this for the removal task:

def copy_directory(root_directory, target_directory):
        import shutil
        import os
        if os.path.isdir(target_directory) == True:
            while True:
                try:
            shutil.rmtree(target_directory)
                except:
                    continue
                break
            shutil.copytree(root_directory, target_directory)
        else:
            shutil.copytree(root_directory, target_directory)

Would this work and what about the copy task then? Are there better options in implementing this?

Thanks!

AzUser1
  • 183
  • 1
  • 14
  • Couldn't you just walk the root directory with `os.walk` and copy each file individually? Put the copy function in a `try` block, and sleep for a second or two then `continue` the loop if an exception is raised. `break` out of the loop if no exception was raised. – GordonAitchJay Jun 10 '22 at 09:29

0 Answers0