the mystery of dirname()

MRAB python at mrabarnett.plus.com
Fri Feb 19 22:05:43 EST 2010


Shashwat Anand wrote:
> In the following code sample :
> 
> def dirname(p):
> 
>     """Returns the directory component of a pathname"""
>     i = p.rfind('/') + 1
> 
>     head = p[:i]
>     if head and head != '/'*len(head):
> 
>         head = head.rstrip('/')
> 
>     return head
> 
> def dirname1(p):
>    i = p.rfind('/') + 1
> 
>    head = p[:i]
>    if head != '/':
> 
>         return head.rstrip('/')    
>    return head
> 
> if __name__ == "__main__":
>    p1 = '/Users/l0nwlf/Desktop'
> 
>    p2 = './'
>    p3 = '/'
>    p4 = '.'
> 
>    print dirname(p1), dirname1(p1)
> 
>    print dirname(p2), dirname1(p2)
> 
>    print dirname(p3), dirname1(p3)
> 
>    print dirname(p4), dirname1(p4)
> 
> OUTPUT:
> 
> /Users/l0nwlf /Users/l0nwlf
> . .
> / /
> 
> dirname() is a function taken from /Lib/posixpath.py. However i did not quite understood the usage of "if head and head != '/'*len(head):" and replaced it with more obvious way in dirname1().
> 
> Am I right to do so ? Is dirname1() more pythonic ? Did I missed any edge cases here ?
> 
What if the path is '//x'? The current dirname would return '//',
whereas dirname1 would return ''.



More information about the Python-list mailing list