path.startswith(dir)?

holger krekel pyth at devel.trillke.net
Sat May 11 12:11:39 EDT 2002


Magnus Lie Hetland wrote:
> >> I've got some code which tests for
> >>
> >>   commonprefix([dir, filename]) == dir
> >>
> >> Assuming that dir ends with a separator (e.g. '/'), it ought to be
> >> just as safe (and more concise) to use
> >>
> >>   filename.startswith(dir)
> >>
> >> no?
> >>
> >> And -- ensuring that dir ends with a separator can be done with
> >>
> >>   dir = join(dir, '')
> >>
> >> This ought to be a safe/platform independent way of doing it, right?

there is one possible problem if you don't 'normpath' filenames.
at least on posix

'/hello/world/huh'.startswith('/hello//world/')

obviously yields false although normalizing both names before
works as expected. It depends, of course, on the guarantees
you have about the filenames beeing compared. If you know
for sure that all your filenames are 'normpath'ed then
you don't need to worry. But as normpath does *not*
interact with your filesystem it is a relatively cheap
function to call. And it makes your code more robust
and hopefully prevents surprises.

Additionally i guess that you are not dealing in any
way with relative filenames in this context, right?

regards,

   holger





More information about the Python-list mailing list