-2

When I try to access an .xls file, I encounter the following error: No such file or directory.

I am sure that I haven't misspelled the name of my file and that my directory is valid. I'm loading other files from this directory and it works, but not with this one file... What's interesting, after typing the code below I can see the names of all my files in the directory:

for f in MyDirectory:
    print(f)

MyDirectory is defined earlier in code as:

MyDirectory = [file for file in os.listdir(r'./folder1/folder2/') if file.endswith(".xlsx") or file.endswith(".xls")]

I can see all the files including the one I cannot load. Do you have any idea what can be the source of this problem and how can I handle it?

Thanks in advance!

anla01
  • 113
  • 10
  • There's way too little code for us to debug anything. – matszwecja Feb 10 '22 at 12:57
  • What is MYDIRECTORY? – DarkKnight Feb 10 '22 at 12:58
  • It is the location of the file I'm trying to load. – anla01 Feb 10 '22 at 13:04
  • @anla01, the item in your `MyDirectory` is only a file name, and it does not contain the **path** preceding to it. If you want to access the file you need to give the path back to the file name, by `os.path.join('./folder1/folder2/', file)` where `file` is one of the items in your `MyDirectory`. – Raymond Kwok Feb 10 '22 at 13:27
  • @RaymondKwok OP is not trying to access anything. She's just printing it out! – DarkKnight Feb 10 '22 at 13:28
  • the code is just printing things out, but the title of the question is `No such file or directory error` so I think the underlying discussion point is about accessing files. – Raymond Kwok Feb 10 '22 at 13:30
  • Possible duplicate of [What exactly is current working directory?](https://stackoverflow.com/questions/45591428/what-exactly-is-current-working-directory) and/or [Difference between `./` and `~/`](https://stackoverflow.com/questions/31435921/difference-between-and/55342466) – tripleee Feb 10 '22 at 13:30
  • I want to access the file. The code with that containts "print" shows me names of all my files in this directory which is good. However, when I try to access it, i'm receiving the error. – anla01 Feb 10 '22 at 15:42

1 Answers1

0

You can either use os.listdir() in conjunction with os.path.join() or you could use glob as follows:

from glob import glob

for filename in glob('./folder1/folder2/*.xls*'):
  with open(filename) as data:
    pass # process file here

This is convenient because glob returns the full path based on the given parameter e.g., ./folder1/folder2/foo.xls

Note that this may not give exactly the same results as you seem to be intending because it will match files ending with xls, xlst, xlsm or indeed any file that has xls at the start of its suffix. You may need to account for that

DarkKnight
  • 19,739
  • 3
  • 6
  • 22