Skip to content

Instantly share code, notes, and snippets.

@answerquest
Last active December 3, 2018 14:24
Show Gist options
  • Select an option

  • Save answerquest/45d62ccd23dfa8ccf1befa541683815d to your computer and use it in GitHub Desktop.

Select an option

Save answerquest/45d62ccd23dfa8ccf1befa541683815d to your computer and use it in GitHub Desktop.
recursiveDropdown : Python3 function: recursively scans 'targetFolder' for all files ending with extension 'ext' (or all files by default), and generates innerHTML for a dropdown menu, with respective sub-folder paths as optgroups.
def recursiveDropdown(targetFolder = '.', ext=''):
'''
Author : Nikhil VJ, http://nikhilvj.co.in
Date: 03 December 2018
recursiveDropdown(targetFolder = '.', ext='')
recursively scans targetFolder for all files ending with extension ext (or all files by default), and generates innerHTML for a dropdown menu, with respective sub-folder paths as optgroups.
'''
if targetFolder.endswith('/'): targetFolder = targetFolder[:-1]
content = '<option value="">Select one</option>'
# traverse through all files, folders under a path recursively. from https://stackoverflow.com/a/2212698/4355695
for root, subdirs, files in os.walk(targetFolder):
folder = root[len(targetFolder)+1:]
targetFiles = [x for x in files if x.endswith(ext)]
targetFiles.sort()
if len(folder) and len(targetFiles):
content += '<optgroup label="{}">'.format(folder)
for file in targetFiles:
filepath = os.path.join(root,file)[len(targetFolder)+1:]
content += '<option value="{}">{}</option>'.format(filepath,file)
if len(folder) and len(targetFiles):
content += '</optgroup>'
return content
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment