开发者

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 fil开发者_JAVA技巧e 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


Start with a list of files:

files = [fname for fname in os.listdir(path) 
               if fname.endswith(('.tgz','.tar'))]

Now you can literally enumerate them:

for item in enumerate(files):
    print "[%d] %s" % item

try:
    idx = int(raw_input("Enter the file's number"))
except ValueError:
    print "You fail at typing numbers."

try:
    chosen = files[idx]
except IndexError:
    print "Try a number in range next time."


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.


def gen_archives(path):
    names = os.listdir(path)
    for name in names:
        if name.endswith(('.tgz', '.tar'))
            yield name

for i, name in enumerate( gen_archives(path) ):
    print "%d. %s" % (i, name)


I really liked Jochen's answer, but disliked the multiple try/except. Here's a variation using a dict instead, which will loop until a valid selection is made.

files = dict((str(i), f) for i, f in
              enumerate(f for f in os.listdir(path) if f.endswith(('.tgz','.tar'))))
for item in sorted(files.items()):
    print '[%s] %s' % item
choice = None
while choice is None:
    choice = files.get(raw_input('Enter selection'))
    if not choice:
        print 'Please make a valid selection'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜