list comprehension to do os.path.split_all ?

Neil Cerutti neilc at norwich.edu
Fri Jul 29 08:40:22 EDT 2011


On 2011-07-29, Dennis Lee Bieber <wlfraed at ix.netcom.com> wrote:
> On Thu, 28 Jul 2011 15:31:43 -0600, Ian Kelly
> <ian.g.kelly at gmail.com> declaimed the following in
> gmane.comp.python.general:
>
>> Using os.sep doesn't make it cross-platform. On Windows:
>> 
>> >>> os.path.split(r'C:\windows')
>> ('C:\\', 'windows')
>> >>> os.path.split(r'C:/windows')
>> ('C:/', 'windows')
>> >>> r'C:\windows'.split(os.sep)
>> ['C:', 'windows']
>> >>> r'C:/windows'.split(os.sep)
>> ['C:/windows']
>
> 	Fine... So normpath it first...
>
>>>> os.path.normpath(r'C:/windows').split(os.sep)
> ['C:', 'windows']
>>>> 

Here's a solution adapted from an initially recursive attempt.
The tests are currently somewhat gnarled to avoid displaying
os.path.sep. A simpler solution probably reimplement os.path.split,
an inconvenient implementation detail.

import os

def split_path(path):
    """Split path into a series of directory names, and return it
    as a list.

    If path is absolute, the first element in the list will be be
    os.path.sep.

    >>> p = split_path('/smith/jones')
    >>> p[0] == os.path.sep
    True
    >>> p[1:]
    ['smith', 'jones']

    >>> split_path('smith/jones')
    ['smith', 'jones']

    >>> split_path('')
    []

    >>> p = split_path('/')
    >>> p[0] == os.path.sep
    True
    >>> len(p)
    1
    """
    head, tail = os.path.split(path)
    retval = []
    while tail != '':
        retval.append(tail)
        head, tail = os.path.split(head)
    else:
        if os.path.isabs(path):
            retval.append(os.path.sep)
        return list(reversed(retval))

if __name__ == '__main__':
    import doctest
    doctest.testmod()

-- 
Neil Cerutti



More information about the Python-list mailing list