the mystery of dirname()
Shashwat Anand
anand.shashwat at gmail.com
Fri Feb 19 22:09:05 EST 2010
But this is posixpath, right ? So '//x' like path will not occur as far as I
guess ?
On Sat, Feb 20, 2010 at 8:35 AM, MRAB <python at mrabarnett.plus.com> wrote:
> 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 ''.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100220/09f83eb6/attachment-0001.html>
More information about the Python-list
mailing list