Hi, I am new to python. I have to devlope a small for code for getting the path of a particular folder, that is given as input to the code, in the other folder. Basically i have to search a folder, not file, inside another folder. I work on windows platform. Can anybody help me.
Python code to search a folder(not file) inside another folder
Collapse
X
-
-
Hi,
I'm not sure what you're trying to do. It sounds like some of the functions in the os.path module might be useful for this. -
The following returns a list of the folders named "dir_name" found under "head_dir". The folder and its subfolders are recursively searched.
[code=Python]import os
def dir_list_folder (head_dir, dir_name):
"""Return a list of the full paths of the subdirectories
under directory 'head_dir' named 'dir_name'"""
dirList = []
for fn in os.listdir(head _dir):
dirfile = os.path.join(he ad_dir, fn)
if os.path.isdir(d irfile):
if fn.upper() == dir_name.upper( ):
dirList.append( dirfile)
else:
# print "Accessing directory %s" % dirfile
dirList += dir_list_folder (dirfile, dir_name)
return dirList
if __name__ == '__main__':
for item in dir_list_folder (r'D:\SDS2_7.1C ', 'mem'):
print item[/code]Example output:
>>> D:\SDS2_7.1C\jo bs\610_CC4_71\m em
D:\SDS2_7.1C\jo bs\613_Ironston e_Bank\mem
D:\SDS2_7.1C\jo bs\614_Embraer\ mem
D:\SDS2_7.1C\jo bs\615_Ironston e_OK\mem
D:\SDS2_7.1C\jo bs\616_Greenway \mem
D:\SDS2_7.1C\jo bs\617_Villa\me m
D:\SDS2_7.1C\jo bs\618_Johnston \mem
D:\SDS2_7.1C\jo bs\619_Okaloosa _Walton\mem
D:\SDS2_7.1C\jo bs\Great_Wolf\m em
>>>
The following does the same thing, but uses os.walk():
[code=Python]import os
def dir_list_folder (head_dir, dir_name):
outputList = []
for root, dirs, files in os.walk(head_di r):
for d in dirs:
if d.upper() == dir_name.upper( ):
outputList.appe nd(os.path.join (root, d))
return outputList
print '\n'.join(dir_l ist_folder(r'D: \SDS2_7.1C\jobs ', 'mem'))[/code]Comment
-
search a folder inside large source base
Code:def dir_list_folder(head_dir, dir_name): dir_list = [] cmd = "cd " + head_dir + " && find . -type d -name " + dir_name + " > /tmp/temp.txt && cd - " (status, output) = commands.getstatusoutput(cmd) if status != 0: print "Error : Failed to execute cmd : " + cmd fp = open("/tmp/temp.txt") lines = fp.readlines() fp.close() for line in lines: dir_list.append(line]) return dir_list
Comment
Comment