Search code examples
pythonenumerate

Enumerate items in a list so a user can select the numeric value


I'm trying to find the most straightforward way to enumerate items in a list so that a user will not be burdened to type a long file name on a command line. The function below shows a user all .tgz and .tar files in a folder ... the user is then allowed to enter the name of the file he wants to extract. This is tedious and syntax-error prone for the user. I would like for a user to just select, say, a numeric value associated with the file (eg.. 1, 2, 3 etc.). Can someone give me some direction on this? Thanks!

  dirlist=os.listdir(path)

  def show_tgz():
     for fname in dirlist:
          if fname.endswith(('.tgz','.tar')):
             print '\n'
             print fname

Solution

  • You can enumerate the items, and print them with an index. You can use a mapping to show continuous numbers to the user, even if the actual indices have gaps:

     def show_tgz():
         count = 1
         indexMapping = {}
         for i, fname in enumerate(dirlist):
             if fname.endswith(('.tgz','.tar')):
                 print '\n{0:3d} - {1}'.format(count, fname)
                 indexMapping[count] = i
                 count += 1
         return indexMapping
    

    You can then use indexMapping to translate the userchoice to the correct index in dirlist.