python中os.path.isabs(path)的分析

这个本身是小组朋友问的问题,感觉不错,我给出的回答

问:

>>> os.path.isabs("/home")

True

>>>os.path.isabs("/home/..")

True

>>>os.path.isabs("home/..")

False

这里第二个应该是相对路径吧? 应该返回False?

答:

首先,给段资料

Thecurrentos.path.isabsdocumentationsays:

>isabs(path)

>ReturnTrueifpathisanabsolutepathname(beginswithaslash).

The"beginswithaslash"partisincorrectsincecertainsystemsusea

differentpathnamenotation.

Forexample,onMacintosh(whereos.sep==":")thisisanabsolute

pathname:

hardDriveName:folderName1:folderName2:fileName.ext

...andthisisarelativeone:

:folderName1:fileName.ext

Moreover,onWindowsos.path.isabs('\\')returnsTruesince'\\'isan

aliasforthecurrentdriveletter(e.g.C:\\)hence,independentlyfrom

whatsaidbefore,thedocumentationshouldincludealsothe"backslash"

term.

ItturnsoutthatonWindowstherearereally4differentkindsofpaths:

1)Completelyrelative,e.g.foo\bar

2)Completelyabsolute,e.g.c:\foo\baror\\server\share

3)Halfbreedswithnodrive,e.g.\foo\bar

4)Halfbreedsrelativetothecurrentworkingdirectoryonaspecificdrive,e.g.c:foo\bar

Python2.5'sos.path.isabs()methodconsidersboth(2)and(3)tobeabsolute;

然后,分析

|这里第二个应该是相对路径吧?应该返回False?

根据,linux中absolute*is*

beginswithaslash,soreturnTrue

说说,第三个吧,你除非在"/"目录下,要不然在其他目录下当然是错的,应为这个路径就不对

而,我在"/"目录下也试了,也返回False,那是因为没有以slash开始

linux中,你只用记下上面那句话就好,其他系统看上面的资料

相关推荐