I need to go through the subdirectories of a given directory, search for excel files and then read their sheet names. A problem occurs when the loop finds an encrypted file. I tried to read files with xlrd and pandas. But I get an error:
xlrd.XLRDError Workbook is encrypted
I made an exception with pass method, but if I do so, the loop breaks at this point and the program stops. What do I have to do to pass that error and move on to the next file? Is there any method to check if the file is encrypted before the method xlrd.open_workbook which collapses the program? Or is it possible to make an exception where I could pass the error and move on?
import codecs
import xlrd
import os
import Tkinter
import tkFileDialog
def pyrexcel(path,file,list):
print 'do now: ' + path + '/' + file
workbook = xlrd.open_workbook(path + '/' + file, encoding_override='windows-1250')
sheet_names = workbook.sheet_names()
for sheet in sheet_names:
list.append(path+"/"+file+"/"+sheet)
def finder(destin,listka,list):
for pliczek in os.listdir(destin):
if os.path.isdir(destin +"/" +pliczek):
finder(destin +"/" +pliczek,listka,list)
elif pliczek[-4:] == ".xls":
pyrexcel(destin,pliczek,list)
elif pliczek[-4:] == ".rar" or pliczek[-4:] == ".zip":
listka.append(destin+pliczek)
root = Tkinter.Tk()
root.withdraw()
listaExcel = []
listaZip = []
dirname = tkFileDialog.askdirectory(parent=root, initialdir="/", title='choose dir to iterate')
print "you choose: " + dirname
try:
finder(dirname,listaZip,listaExcel)
except xlrd.XLRDError as e:
print e.message
pass
plik = codecs.open((dirname + "/listaZIP.txt"), 'w', "utf-8")
for item in listaZip:
plik.write("%s\n" % item)
plik.close()
plik = codecs.open((dirname + "/listaExcel.txt"), 'w', "utf-8")
for item in listaExcel:
plik.write("%s\n" % item)
plik.close()