列出列表中的项目以供用户选择数值
我正在寻找一种最简单的方法来列出列表中的项目,这样用户就不需要在命令行上输入很长的文件名。下面的这个函数会显示一个文件夹中的所有 .tgz 和 .tar 文件……然后用户可以输入他想要提取的文件名。这对用户来说很麻烦,而且容易出错。我希望用户只需选择一个与文件相关的数字值(例如:1、2、3等等)。有人能给我一些建议吗?谢谢!
dirlist=os.listdir(path)
def show_tgz():
for fname in dirlist:
if fname.endswith(('.tgz','.tar')):
print '\n'
print fname
4 个回答
3
我很喜欢Jochen的回答,但不太喜欢里面有很多次的try/except。这里有一个不同的写法,使用字典来代替,这样会一直循环,直到用户做出一个有效的选择。
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'
8
首先,你需要准备一个文件列表:
files = [fname for fname in os.listdir(path)
if fname.endswith(('.tgz','.tar'))]
现在你可以真的去列举
这些文件了:
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."
3
你可以列出所有的项目,并给它们加上编号。即使实际的编号中有空缺,你也可以用一个映射来给用户显示连续的数字:
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
然后,你可以使用 indexMapping
来把用户选择的数字转换成 dirlist
中的正确编号。