list comprehension to do os.path.split_all ?

Carl Banks pavlovevidence at gmail.com
Fri Jul 29 15:30:20 EDT 2011


On Thursday, July 28, 2011 2:31:43 PM UTC-7, Ian wrote:
> On Thu, Jul 28, 2011 at 3:15 PM, Emile van Sebille <em... at fenx.com> wrote:
> > On 7/28/2011 1:18 PM gry said...
> >>
> >> [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.
> >>
> >
> > Why not just split?
> >
> > '/home/gyoung/hacks/pathhack/foo.py'.split(os.sep)
> 
> 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']

It's not even fullproof on Unix.

'/home//h1122/bin///ghi/'.split('/')

['','home','','bin','','','ghi','']

The whole point of the os.path functions are to take care of whatever oddities there are in the path system.  When you use string manipulation to manipulate paths, you bypass all of that and leave yourself open to those oddities, and then you find your applications break when a user enters a doubled slash.

So stick to os.path.


Carl Banks



More information about the Python-list mailing list