欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

【Python3笔记】关于os.path.isabs()

程序员文章站 2022-03-18 15:33:17
先来看几个使用os,path.isabs()的例子: 很显然,第一个路径是没有问题,而后面都是我随便输入的一串字符,为什么有的返回True有的返回False呢? 我查看了Python3.5的文档,发现了这样一句话: os.path.isabs(path) Return True if path is ......

先来看几个使用os,path.isabs()的例子:

【Python3笔记】关于os.path.isabs()

很显然,第一个路径是没有问题,而后面都是我随便输入的一串字符,为什么有的返回true有的返回false呢?

 

我查看了python3.5的文档,发现了这样一句话:

os.path.isabs(path)

return true if path is an absolute pathname. on unix, that means it begins with a slash, on windows that it begins with a (back)slash after chopping off a potential drive letter.

也就是说在window系统下,如果输入的字符串以" / "开头,os.path.isabs()就会返回true,那么第四个例子就可以理解了。

 

而第二个和第三个有什么区别呢?不是都应该返回false吗?

查阅资料后我找到了下面这段话:

the current os.path.isabs documentation says:
> isabs(path) 
>    return true if path is an absolute pathname (begins with a slash). 
the "begins with a slash" part is incorrect since certain systems use a
different pathname notation.
for example, on macintosh (where os.sep == ":") this is an absolute
pathname:
harddrivename:foldername1:foldername2:filename.ext
...and this is a relative one:
:foldername1:filename.ext
moreover, on windows os.path.isabs('\\') returns true since '\\' is an
alias for the current drive letter (e.g. c:\\) hence, independently from
what said before, the documentation should include also the "backslash"
term.
it turns out that on windows there are really 4 different kinds of paths:
1) completely relative, e.g. foo\bar
2) completely absolute, e.g. c:\foo\bar or \\server\share
3) halfbreeds with no drive, e.g. \foo\bar
4) halfbreeds relative to the current working directory on a specific drive, e.g. c:foo\bar
python 2.5's os.path.isabs() method considers both (2) and (3) to be absolute;

虽然是python2的,但是这和python3应该没什么区别。从上面这段话可以知道,在windows系统上,以“  //  "开头的字符串,os.path.isabs也会返回true

然后我们又可以知道:

【Python3笔记】关于os.path.isabs()

这就能解释为什么第二个返回false而第三个返回true了。