Newbie lists question

Peter Hansen peter at engcorp.com
Wed Aug 15 01:36:11 CEST 2001


Jeff Shannon wrote:
> 
> Wolfe Maykut wrote:
> 
> > for file in backupdir:
> >     filename = string.split(file, '/')[-1]
> >     prefix = string.split(filename,'.')[0]
> 
> >>> for file in backupdir:
> ...     filename = os.path.split(file)[1]  # you only need the filename
> component, not the path component
> ...     prefix = os.path.splitext(filename)[0]  # you only need the root
> part, not the extension
> 
> While portability may not be an issue for this particular script, it's
> really a good idea to be in the habit of using os.path for all your path
> manipulations, rather than the usual string functions.  (It's also a good
> idea to use string methods instead of the string module, unless you're
> targetting older Python installations.)

More important even than portability, is correct functionality.

I noticed that the original code doesn't work the same as 
yours, probably because yours is correct. :)  The original
takes everything *before* the first period in the filename,
while yours takes everything up to the last period.

The problem with avoiding os.path is not that you are 
missing portability, nor even that you are needlessly
reinventing the wheel.  The problem is that you are 
probably writing buggy code, whereas os.path should
be pretty reliable by now...

(Same logic applies to using lots of complicated string
operations when the 're' module could do it better. 
Not 'cause it's faster, nor easier to read, etc.... just
because it's more likely to be correct.)

-- 
----------------------
Peter Hansen, P.Eng.
peter at engcorp.com



More information about the Python-list mailing list