pros and cons between os.path.exists vs os.path.isdir

PythonDirectoryos.path

Python Problem Overview


I'm checking to see if a directory exists, but I noticed I'm using os.path.exists instead of os.path.isdir. Both work just fine, but I'm curious as to what the advantages are for using isdir instead of exists.

Python Solutions


Solution 1 - Python

os.path.exists will also return True if there's a regular file with that name.

os.path.isdir will only return True if that path exists and is a directory, or a symbolic link to a directory.

Solution 2 - Python

Just like it sounds like: if the path exists, but is a file and not a directory, isdir will return False. Meanwhile, exists will return True in both cases.

Solution 3 - Python

os.path.isdir() checks if the path exists and is a directory and returns TRUE for the case.

Similarly, os.path.isfile() checks if the path exists and is a file and returns TRUE for the case.

And, os.path.exists() checks if the path exists and doesn’t care if the path points to a file or a directory and returns TRUE in either of the cases.

Solution 4 - Python

Most of the time, it is the same.

But, path can exist physically whereas path.exists() returns False. This is the case if os.stat() returns False for this file.

If path exists physically, then path.isdir() will always return True. This does not depend on platform.

Solution 5 - Python

> os.path.exists(path) > Returns True if path refers to an existing path. An existing path can > be regular files > (http://en.wikipedia.org/wiki/Unix_file_types#Regular_file), but also > special files (e.g. a directory). So in essence this function returns > true if the path provided exists in the filesystem in whatever form > (notwithstanding a few exceptions such as broken symlinks). > > os.path.isdir(path) > in turn will only return true when the path points to a directory >

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1834048View Question on Stackoverflow
Solution 1 - PythonPavel AnossovView Answer on Stackoverflow
Solution 2 - PythonFredrick BrennanView Answer on Stackoverflow
Solution 3 - PythonManozView Answer on Stackoverflow
Solution 4 - PythonkiriloffView Answer on Stackoverflow
Solution 5 - PythonJan KunigkView Answer on Stackoverflow