list comprehension to do os.path.split_all ?

Alexander Kapps alex.kapps at web.de
Thu Jul 28 17:06:22 EDT 2011


On 28.07.2011 22:44, Ian Kelly wrote:
> On Thu, Jul 28, 2011 at 2:18 PM, gry<georgeryoung at gmail.com>  wrote:
>> [python 2.7] I have a (linux) pathname that I'd like to split
>> completely into a list of components, e.g.:
>>    '/home/gyoung/hacks/pathhack/foo.py'  -->    ['home', 'gyoung',
>> 'hacks', 'pathhack', 'foo.py']
>>
>> os.path.split gives me a tuple of dirname,basename, but there's no
>> os.path.split_all function.
>>
>> I expect I can do this with some simple loop, but I have such faith in
>> the wonderfulness of list comprehensions, that it seems like there
>> should be a way to use them for an elegant solution of my problem.
>> I can't quite work it out.  Any brilliant ideas?   (or other elegant
>> solutions to the problem?)
>
> path = '/home/gyoung/hacks/pathhack/foo.py'
> parts = [part for path, part in iter(lambda: os.path.split(path), ('/', ''))]
> parts.reverse()
> print parts
>
> But that's horrendously ugly.  Just write a generator with a while
> loop or something.


pathname = '/home/gyoung/hacks/pathhack/foo.py'
parts = [part for part in pathname.split(os.path.sep) if part]
print parts

['home', 'gyoung', 'hacks', 'pathhack', 'foo.py']



More information about the Python-list mailing list