AzUser1
AzUser1

Reputation: 193

Retry a copy acitivity in python if a network error is given?

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!

Upvotes: 1

Views: 281

Answers (0)

Related Questions