Search code examples
pythonxlrd

Python XLRD no such file or directory


I have a script working where I can open files if I pass the file name but now the number of files is increasing and it doesn't make sense to have to run the script on each file individually. So I decided to let python read al files in a directory.

for root, dirs, files in os.walk("Approved_LRPMP_Worksheets/"):
    for fyle in files:
        if fyle.endswith(".xlsx"):
            print fyle
            book = xlrd.open_workbook(fyle)
            print "book opened"

The output from this is:

I found a file: Agoura Hills LRPMP Review Sheet.xlsx
Traceback (most recent call last):
  File "test.py", line 21, in <module>
    book = xlrd.open_workbook(fyle)
File "/Library/Python/2.7/site-packages/xlrd/__init__.py", line 394, in open_workbook
  f = open(filename, "rb")
IOError: [Errno 2] No such file or directory: 'Agoura Hills LRPMP Review Sheet.xlsx'

The file is clearly being read, the name of the file is output in the command line just before I get the error. I feel like this is something simple that I should be catching but it has evaded me for the last 30 minutes...


Solution

  • It was a simple fix, I was being stupid.

    for root, dirs, files in os.walk("Approved_LRPMP_Worksheets/"):
        for fyle in files:
            if fyle.endswith(".xlsx"):
                print "I found a file: " + fyle
                fyleName = "Approved_LRPMP_Worksheets/"+fyle
                book = xlrd.open_workbook(fyleName)
    

    And its done