Safe File Copying Function Using shutil.copy2

  • Share this:

Code introduction


This function attempts to safely copy a file using the shutil.copy2 method. If an error occurs, it will catch the exception and return False.


Technology Stack : shutil, shutil.copy2, shutil.Error, IOError

Code Type : Function

Code Difficulty : Intermediate


                
                    
import shutil
import random

def copyfile_safe(src, dst):
    try:
        shutil.copy2(src, dst)
        return True
    except (shutil.Error, IOError) as e:
        print(f"Error: {e.strerror}")
        return False