Mostly Linux & Python syntax notes and hyperlinks.

Monday, March 16, 2015

python: return parent path containing input string

I wrote this to isolate higher-level directory paths from those listed in environment variables.

import os

def path_including_string(big_path,small_string): 
   """ Return parent directory of big_path whose name includes small_string
       Searches from end, so if small_string in two subdirectories, 
          then this returns the lowest (longest) path
   Keyword arguments:
   :param big_path: input path to be cut down
   :param small_string: string that defines where to end returned path
   """
   assert small_string in big_path
   head,tail=os.path.split(big_path)
   while small_string not in tail:
     big_path=head
     head,tail=os.path.split(big_path)
   return big_path


Simple Test:
>>> big_path="C:\\abc\\def\\ghi\\jkl\\cdef\\qr\\s\\tuv"
>>> path_including_string(big_path,"de") 
 'C:\\abc\\def\\ghi\\jkl\\cdef' 

Test using an environment variable:

>>> mylist=os.environ.get('LIB').split(';')
>>> for p in mylist:
...     if 'SDK' in p:
...         print p
...         print path_including_string(p,'SDK')
...        
C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\\PlatformSDK\lib
C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\\PlatformSDK
C:\Program Files\Microsoft SDKs\Windows\v6.0A\\lib
C:\Program Files\Microsoft SDKs
 


No comments:

Post a Comment