Here’s what I’ve got so far:
project_dir = '/my/project/dir'
project_depth = len(project_dir.split(os.path.sep))
xml_files = []
for dirpath, dirnames, filenames in os.walk(project_dir):
for filename in fnmatch.filter(filenames, '*.xml'):
dirs = dirpath.split(os.path.sep)[project_depth:]
print(dirs)
xml_files.append(os.path.join(dirpath,filename))
Essentially what I want to do is spit out my project directory structure with all the XML files as an HTML tree (using <ul>). I can get all the files this way, but I can’t seem to figure out how to organize them into a tree.
With the way this os.walk works, I don’t know when I’ve gone in a level deeper, or if I’m still traversing the same directory.
for dirpath, dirnames, filenames in os.walk(project_dir):
xml_files = fnmatch.filter(filenames, '*.xml')
if len(xml_files) > 0:
out.write('<li>{0}<ul>'.format(dirpath))
for f in xml_files:
out.write('<li>{0}</li>'.format(f))
out.write('</ul></li>')
out.write('</ul>')
This gives me a list of directories and all the files underneath them, but I still can’t figure out how to split the directory path so that it’s nested too.
os.walkmight not be the best solution if you care about the hierarchy. A simpler solution would probably be just do useos.listdirwithos.path.isdirto traverse your tree recursively.