Search code examples
pythonexcelpython-2.7filenames

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 xlrd.open_workbook() can then use the element in the array to open that file?


Solution

  • 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):
        try:
            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)