Python: os.path.exists vs os.path.isdir

匿名 (未验证) 提交于 2019-12-03 02:44:02

问题:

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

回答1:

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.



回答2:

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.



回答3:

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.



回答4:

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!