Pavel Penev Pavel Penev - 2 months ago 9
Python Question

How can I check how much of a path exists in python

Let's say on my filesystem the following directory exists:

/foo/bar/


In my python code I have the following path:

/foo/bar/baz/quix/


How can I tell that only the
/foo/bar/
part of the path exists?

I can walk the path recursively and check it step by step, but is there an easier way?

Answer

No easy function in the standard lib but not really a difficult one to make yourself.

Here's a function that takes a path and returns only the path that does exist.

In [129]: def exists(path):
     ...:     if os.path.exists(path): return path
     ...:     return exists(os.path.split(path)[0])
     ...:

In [130]: exists("/home/sevanteri/src/mutta/oisko/siellä/jotain/mitä/ei ole/")
Out[130]: '/home/sevanteri/src'
Comments