tags:

views:

60

answers:

1

Hi, I'm a python newbie with a problem too hard to tackle.

I have a string defining a path, were all the spaces have been converted to underscores. How can I find if it corresponds to a real path?

e.g. a string like /some/path_to/directory_1/and_to/directory_2
with a real path: /some/path_to/directory 1/and_to/directory 2

notice that the real path can contain BOTH spaces and underscores.

How can I feed it to os.path.exists() ???

thanks alessandro

+5  A: 

Use glob but replacing every underscore with a range [ _]:

import glob
glob.glob('/some/path_to/directory_1/and_to/directory_2'.replace('_', '[ _]'))

Note that this will fail if your path contains the character [. You can fix this by first replacing [ with [[].

Mark Byers
...by *first* replacing `[` with `[[]`.
Constantin
like this? p1='/some/path_to/directory_1/and_to/directory_2'.replace('_', '[ _]') p2='/some/path_to/directory_1/and_to/directory_2'.replace('[', '[[]') glob.glob(p2)
alessandro
+1: Those who forget about the glob module are doomed to attempt to recreate it badly for a few minutes before hitting refresh on the SO question to see an answer from someone who hasn't.
MattH
You'll also need to "escape" `?` and `*` in the same way.
Glenn Maynard
escape ?* ??? sorry, python newbie here - how do I do it?
alessandro