tags:

views:

216

answers:

6

Hi,

What is the most pythonic way to find presence of every directory name ['spam', 'eggs'] in path e.g. "/home/user/spam/eggs"

Usage example (doesn't work but explains my case):

dirs = ['spam', 'eggs']
path = "/home/user/spam/eggs"
if path.find(dirs):
    print "All dirs are present in the path"

Thanks

+2  A: 
names = ['spam', 'eggs']
dir   = "/home/user/spam/eggs"

# Split into parts
parts = [ for part in dir.split('/') if part != '' ]

# Rejoin found paths
dirs  = [ '/'.join(parts[0:n]) for (n, name) in enumerate(parts) if name in names ]

Edit : If you just want to verify whether all dirs exist:

parts = "/home/user/spam/eggs".split('/')

print all(dir in parts for dir in ['spam', 'eggs'])
Dario
This will obviously work, but looks quiet complex for such a simple task. Thanks, anyway:)
Dmitry Gladkov
A: 

A one liner using generators (using textual lookup and not treating names as anything to do with the filesystem - your request is not totally clear to me)

[x for x in dirs if x in  path.split( os.sep )]
Mark
A: 

Try this:

dirs = ['spam', 'eggs']
path = "/home/user/spam/eggs"

if not set(dirs).difference(path.split(os.sep)):
    print "All dirs are present in the path"

This builds a set out of all the dirs you want, then removes the directories in the path form it. If the resulting set is empty, all directories were removed, and that means they all were in the path.

Petr Viktorin
+5  A: 

Looks line you want something like...:

if all(d in path.split('/') for d in dirs):
   ...

This one-liner style is inefficient since it keeps splitting path for each d (and split makes a list, while a set is better for membership checking). Making it into a 2-liner:

pathpieces = set(path.split('/'))
if all(d in pathpieces for d in dirs):
   ...

vastly improves performance.

Alex Martelli
A: 

Maybe this is what you want?

dirs = ['spam', 'eggs']
path = "/home/user/spam/eggs"
present = [dir for dir in dirs if dir in path]
Chazadanga
+8  A: 

set.issubset:

>>> set(['spam', 'eggs']).issubset('/home/user/spam/eggs'.split('/'))
True
J.F. Sebastian