I am trying to find the path that is located one directory up and contains a specific word. For example, the path I am trying to find here will be /whatever/path/2343blah344
oldpath = '/whatever/path/itis'
newpath = os.path.join(os.path.dirname(oldpath), '/*blah*')
When I print newpath, it only shows up as /*blah, so I'm pretty sure * did not work or this is not the right way to approach it.
2 Answers 2
Just to be clear, os.path.join works on text strings. It does not actually compare them with the underlying operating system in any sophisticated way. This is useful both for effeciency and for when you want to create paths that aren't tied to the computer this is currently executing on.
As Burhan Khalid suggested, glob is the best way to achieve what you actually want. If you want to do it all with the os library for some reason, then you can do something like using os.walk to get all the possibilities and then filter through those.
Comments
On the basis that you're only expecting one match...
import glob
oldpath = '/whatever/path/itis'
newpath = glob.glob(os.path.join(os.dirname(oldpath), '*blah*/'))[0]
os.path.joinshould return always lists(even if with only one path), or it has to return a string if there's only one result and a list of strings if there are more. This does not seem quite right for such a function. If you want shell expansion style useglob(as already suggested) orfnmatchfor more general use cases.'/*blah*'begins with a slash,joininterprets it as an absolute path and disregards the first argument. See here for details.