list comprehension to do os.path.split_all ?

Alan Meyer ameyer2 at yahoo.com
Thu Jul 28 16:40:57 EDT 2011


On 7/28/2011 4:18 PM, gry 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?)
>
> -- George

This is not properly portable to all OS, but you could simply split on 
the slash character, e.g.,

     pathname.split('/')

   Alan



More information about the Python-list mailing list