7

I'm learning Python 3 and trying to write a script that will copy a directory. I'm using shutil.copytree. From the Python documentation it says:

If exception(s) occur, an Error is raised with a list of reasons.

This exception collects exceptions that are raised during a multi-file operation. For copytree(), the exception argument is a list of 3-tuples (srcname, dstname, exception).

In the example they do this:

 except Error as err:
            errors.extend(err.args[0])

Here is my script:

def copyDirectory(src, dest):

    errors = []

    try:
        shutil.copytree(src, dest)
     except Error as err:
            errors.extend(err.args[0])

source="C:/Users/MrRobot/Desktop/Copy"      
destination="C:/Users/MrRobot/Desktop/Destination"

copyDirectory(source, destination)
moveDirectory(destination,"I:/")

Questions:

  1. How do you properly catch an exception that might occur when using shutil.copytree (assuming my above script is incorrect)?

  2. How then would you view the errors that occurred, would I loop through the errors array?

Emma Geller-Green
  • 297
  • 1
  • 4
  • 9

2 Answers2

9

You need to either include the module name when you catch the exception:

except shutil.Error as err:

Or import it explicitly:

from shutil import copytree, Error

# the rest of your code...

try:
    copytree(src, dest)
 except Error as err:
        errors.extend(err.args[0])

To view the traceback and exception information, you have a few options:

  1. Don't catch the exception. Your script will be halted and all the error information will be printed.

  2. If you want the script to continue, then you're really asking a duplicate of this SO question. I would reference that question; the accepted answer is written very well.

And by the way, you should avoid calling it an array. This particular exception object has a list of tuples, and arrays are an entirely different data structure.

Community
  • 1
  • 1
skrrgwasme
  • 9,358
  • 11
  • 54
  • 84
0

You can use OSError to handle it :

import shutil 

def removeDirectory(directory):
    try:
        shutil.rmtree(directory)
    except OSError as err:
        print(err)

removeDirectory('PathOfDirectoryThatDoesntExist')

OUTPUT :

[Errno 2] No such file or directory: './PathOfDirectoryThatDoesntExist'

Kevin Sabbe
  • 1,412
  • 16
  • 24