the mystery of dirname()

Shashwat Anand anand.shashwat at gmail.com
Fri Feb 19 21:25:40 EST 2010


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 ?

Regards,
~l0nwlf
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100220/148572e7/attachment.html>


More information about the Python-list mailing list