Python os.path.exists 与 os.path.isdir 之间的优缺点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15077424/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
pros and cons between os.path.exists vs os.path.isdir
提问by user1834048
I'm checking to see if a directory exists, but I noticed I'm using os.path.existsinstead of os.path.isdir. Both work just fine, but I'm curious as to what the advantages are for using isdirinstead of exists.
我正在检查目录是否存在,但我注意到我正在使用os.path.exists而不是os.path.isdir. 两者都工作得很好,但我很好奇使用isdir而不是exists.
采纳答案by Pavel Anossov
os.path.existswill also return Trueif there's a regular file with that name.
os.path.existsTrue如果有具有该名称的常规文件,也将返回。
os.path.isdirwill only return Trueif that path exists and is a directory, or a symbolic link to a directory.
os.path.isdir仅True当该路径存在并且是目录或目录的符号链接时才会返回。
回答by Fredrick Brennan
Just like it sounds like: if the path exists, but is a file and not a directory, isdirwill return False. Meanwhile, existswill return Truein both cases.
就像听起来一样:如果路径存在,但它是一个文件而不是目录,isdir则将返回False. 同时,在这两种情况下exists都会返回True。
回答by kiriloff
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.
但是,路径可以物理存在,而path.exists()返回 False。如果 os.stat() 为该文件返回 False,就是这种情况。
If path exists physically, then path.isdir()will always return True. This does not depend on platform.
如果路径物理存在,path.isdir()则将始终返回 True。这与平台无关。
回答by Jan Kunigk
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
os.path.exists(path) 如果 path 指的是现有路径,则返回 True。现有路径可以是常规文件(http://en.wikipedia.org/wiki/Unix_file_types#Regular_file),也可以是特殊文件(例如目录)。因此,本质上,如果提供的路径以任何形式存在于文件系统中(尽管有一些例外,例如损坏的符号链接),则该函数返回 true。
os.path.isdir(path) 反过来只会在路径指向目录时返回 true
回答by Manoz
os.path.isdir()checks if the path exists and is a directory and returns TRUE for the case.
os.path.isdir()检查路径是否存在并且是一个目录,并在这种情况下返回 TRUE。
Similarly, os.path.isfile()checks if the path exists and is a file and returns TRUE for the case.
类似地,os.path.isfile()检查路径是否存在并且是一个文件,并在这种情况下返回 TRUE。
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.
并且,os.path.exists()检查路径是否存在并且不关心路径是指向文件还是目录并在任何一种情况下返回 TRUE。

