0

The following code is being used to copy Excel documents to a new directory but I am getting some different errors which prevent the script from completing.

import os
from shutil import copy
for root, dirs, files in os.walk("T:/DIR"):
    for file in files:
        if file.endswith(".xls") or file.endswith('xlsx'):
            copy(os.path.join(root, file),"C:/DIR")

The errors range from permission errors, to file not found errors. I need to make the script pass these and continue. There are tutorials on exception handling but I don't know how to actually use them with my code. For example, this link says to use:

except:
    pass

but where exactly am I supposed to put this in the code?

david_10001
  • 492
  • 1
  • 6
  • 22

1 Answers1

1
import os
from shutil import copy
for root, dirs, files in os.walk("T:/DIR"):
    for file in files:
        if file.endswith(".xls") or file.endswith('xlsx'):
            try:
                # attempt condition that may cause error
                copy(os.path.join(root, file),"C:/DIR")
            except:
                # handle exception here.
                pass

It is usually a good idea to handle the type of exception with each use of except:. You could also log the errors in the except: section.

Read the Python tutorial on Errors and Exceptions for better understanding.

michael_heath
  • 5,262
  • 2
  • 12
  • 22