Using Python how do you bypass or move an excel file in a folder if it is corrupt?

Hi,

I am using the following Python code in a bigger script, but when some excel files (.xls) are corrupt I get the following error:

raise XLRDError('Unsupported format, or corrupt file: ' + msg)

XLRDError: Unsupported format, or corrupt file: Expected BOF record; found b'X\xcf\x13\xe0\xa1\xb9\x1a\xe1'


It fails when opening a workbook that is corrupt (wb = xlrd.open_workbook(filepath)), which ends the script. Is there a way I can modify the script to bypass the corrupt excel file or move it somewhere else and allow the script to move on?


import pandas as pd
import os
import xlrd
import shutil
from os import path

for subdir, dirs, files in os.walk(r'C:\Temp'):
    for file in files:
        filepath = subdir + os.sep + file
        
        
        wb = xlrd.open_workbook(filepath)

Open in new window

crompnkData Management SpecialistAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

David FavorLinux/LXD/WordPress/Hosting SavantCommented:
Check docs for the wb = xlrd.open_workbook() call you're making.

1) The wb variable will either be NULL... or...

2) There will be some other error message returned some way.

You'll either check for wb == NULL or the other error return code + if you get any failure, then you just skip the failing file (or move it or delete it), then keep processing files which return success.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
python3

From novice to tech pro — start learning today.