The 'os' module in Python says "No such file or directory" even when there definitely is one

Question:

I am trying to open an .npy file. However, Python keeps saying that there exists no such file or directory, even when there is one…

To make sure that it isn’t an issue of giving correct path names, I changed my directory to the folder that contains the .npy file that I want. Then used list.dir() and used it to use np.load (the code is below):

os.chdir(filename_dir) #filename_dir is the directory I want to get to that contains the npy file I want)
the_path=os.path.join(os.getcwd()+os.listdir()[-1]) #i.e. I did this to make sure that the directory is correct
data=np.load(the_path)

However, I got the error, [Errno 2] No such file or directory: .......
The error occurs when I try np.load. I couldn’t understand this because I explicitly made the path the_path from what Python says exists.

Asked By: Danny Han

||

Answers:

Try adding r. For example,

file_path = r"filePath"

This may work…

Answered By: Anonymous

I think this is the problem…

Windows (by default) has a maximum path length of 260 characters. The absolute path to this file exceeds that limit. The filename alone is 143 characters.

It looks as though even if you try to access the file using a relative path (i.e., chdir() to the appropriate folder then specify just the filename), numpy is probably working out the absolute path then failing.

You have said that renaming the file to something much shorter solves the problem but is impractical due to the high numbers of files that you need to process.

There is a Windows Registry key that can be modified to enable long pathnames: ComputerHKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlFileSystemLongPathsEnabled

Changing that may help.

Or you could buy a Mac

Answered By: Cobra
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.