0

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()
Kamu
  • 23
  • 6

1 Answers1

0

continue should accomplish what you want as listed here:

"pass simply does nothing, while continue goes on with the next loop iteration. In your example, the difference would become apparent if you added another statement after the if: After executing pass, this further statement would be executed. After continue, it wouldn't."

Also I found this answer while trying to look for a way to find out if an Excel file is encrypted via python so thank you! :D

Source: Is there a difference between `continue` and `pass` in a for loop in python?

Python Docs: https://docs.python.org/2/reference/simple_stmts.html#continue

Community
  • 1
  • 1
Max Humphrey
  • 65
  • 1
  • 9