Pavel Penev Pavel Penev - 1 year ago 69
Python Question

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

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


In my python code I have the following path:


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

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

Answer Source

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'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download