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...@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
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to