Reputation: 67
I have a script where I'm walking through a list of passed (via a csv file) paths. I'm wondering how I can determine if the path I'm currently working with has been previously managed (as a subdirectory of the parent).
I'm keeping a list of managed paths like this:
pathsManaged = ['/a/b', '/c/d', '/e']
So when/if the next path is '/e/a'
, I want to check in the list if a parent of this path is present in the pathsManaged
list.
My attempt so far:
if any(currPath in x for x in pathsManaged):
print 'subdir of already managed path'
This doesn't seem to be working though. Am I expecting too much from the any command. Are there any other shortcuts that I could use for this type of look-up?
Thanks
Upvotes: 0
Views: 226
Reputation: 6387
If I understand you correctly, you want to check if any of pathsManaged
is part of currPath
, but you are doing this other way around.
Depending on what you want, one of this should work for you:
any(x in currPath for x in pathsManaged)
any(currPath.startswith(x) for x in pathsManaged)
os.path.dirname(currPath) in pathsManaged
Upvotes: 0
Reputation: 74645
Perhaps:
from os.path import dirname
def parents(p):
while len(p) > 1:
p = dirname(p)
yield p
pathsManaged = ['/a/b', '/c/d', '/e']
currPath = '/e/a'
if any(p in pathsManaged for p in parents(currPath)):
print 'subdir of already managed path'
prints:
subdir of already managed path
Upvotes: 2
Reputation: 31250
Assuming that pathsManaged contains absolute paths (otherwise I think all bets are off), then you could make currPath an absolute path and see if it starts with any of the paths in pathsManaged. Or in Python:
def is_path_already_managed(currPath):
return any(
os.path.abspath(currPath).startswith(managed_path)
for managed_path in pathsManaged)
Also conceptually I feel pathsManaged should be a set
, not a list
.
Upvotes: 0