0

I am developing a Python script for work that will open an Excel file from a particular directory without knowing what the filename is. currently I am opening the file like this. Also opening particular sheet.

book = xlrd.open_workbook(r'D:\New folder\EXCELUPLOAD.xls')
sheet = book.sheet_by_name("Sheet3")

I want to open the file without giving its name, either using its extension or using first few letters etc.

book = xlrd.open_workbook(r'D:\New folder\_.xls or Exce_')
sheet = book.sheet_by_name("Sheet3")

Is there any way around to do this?

Adriaan
  • 17,741
  • 7
  • 42
  • 75
GD201
  • 13
  • 3
  • You could write some separate code that gets the filename from that directory based on your conditions and then passes that to `open_workbook`. – Mihai Chelaru Dec 01 '22 at 14:45
  • Actually, I'm a new to python so don't know how to do it. Can you please give an example to understand this better? – GD201 Dec 01 '22 at 14:47
  • 2
    What if there are a few files with that extension? And that same prefix? – Tomerikoo Dec 01 '22 at 14:48
  • @Tomerikoo There will be no other files as I am storing only one file in that particular directory. I just want to know how I can do this. – GD201 Dec 01 '22 at 14:52
  • Check the duplicate. Assuming your directory has one file, list "all" files and choose the first (only) one... – Tomerikoo Dec 01 '22 at 14:54
  • @Tomerikoo Thanks for the reply but I just want to know that can I open the file only with extension or using some letters with xlrd. – GD201 Dec 01 '22 at 14:58
  • No. But you can do it with `glob` to find your file - `for file in glob.glob("*.xls"):` - and then open it with xlrd – Tomerikoo Dec 01 '22 at 15:00
  • Okay, Thank you for your suggestion. I will try it using glob. – GD201 Dec 01 '22 at 16:00

0 Answers0