Matthew Stevenson Matthew Stevenson - 5 months ago 35
Python Question

Opening unknown Excel filename using Python

I am developing a Python script for work that will open an Excel file from a particular directory without knowing what the filename is. The directory is fixed and controlled in a way so that the user can get to the directory where the file is located. There will only be one Excel file in each directory. Is it possible to have a xlrd open command that opens an Excel file without specifying the filename in the given directory?

Or, is there a way to go around this and have a function that searches for .xlsx extensions in a given directory and then stores these filenames in an array so that

can then use the element in the array to open that file?


Here's a simple function that wraps open_workbook(), using glob.glob() to pass an arbitrary .xlsx file in folder to it:

import os.path
from glob import glob
from xlrd import open_workbook

def open_arbitrary_workbook(folder, *args, **kwargs):
        path = glob(os.path.join(folder, "*.xlsx"))[0]
    except IndexError:
        raise IOError("No .xlsx files found in %r" % folder)
    return open_workbook(path, *args, **kwargs)