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!

asked Jun 9, 2022 at 6:55
1
  • 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. Commented Jun 10, 2022 at 9:29

0

Know someone who can answer? Share a link to this question via email, Twitter, or Facebook.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.