Python: Why does os.getcwd() sometimes crash with OSError?

Question:

I have this program that at one point accesses os.getcwd(), but some times, depending on where the program has gone before getting to that line, it crashes with the message “OSError: [Errno 2] No such file or directory”.
I cannot figure out what i can do wrong then calling os.getcwd(). There’s no arguments, and there should always be a current working directory, right?

Asked By: Eskil

||

Answers:

The current directory may have been deleted by another process.

Answered By: Marco Mariani

You might get that error if the current working directory has been deleted. Programs that are working in a particular directory don’t automatically notice if the directory gets deleted; as far as the program is concerned, the CWD is just a string, at least until you do something like os.getcwd() that actually accesses that path on the filesystem. So it’s possible to have a current directory that doesn’t exist.

Without knowing more about your program and its execution environment, I couldn’t tell you if that is what’s actually happening, though.

Answered By: David Z

You would get that error if your current directory no longer exists (it is deleted).

Answered By: gauteh

It is also possible to get this error when working with an encrypted filesystem and if the partition containing the working directory went back to a “locked” state. In my case, a README file was available at the mounting point of the partition explaining how to unlock the partition again. It could depend of the encryption system and settings.

Once the partition unlocked again, to get rid of the error, a change directory is needed to reset the working directory. Even if the target directory is the directory where you already are.

Answered By: djoproject

Sommeone probably erased your filesystem while you had the Python open.

That is why Python is stating that it could not be found. This had happened to me.

Answered By: jimp
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.