import os
path="/root/Desktop"
dirList=os.listdir(path)
for i in range(0,len(dirList)): # generate an index an loop over it
print "%d)" % (i+1), dirList[i] # print a selection number matching each file
selected = raw_input("Select a file above: ")
selected = int(selected) # cast the input to int
print "You have selected:", dirList[selected-1] # you can get the corresponding entry!
for i, fname in enumerate(dirList):
print "%s) %s" % (i + 1, fname)
selectedInt = int(raw_input("Select a file above: "))
selected = dirList[selectedInt - 1]
import os
path="/root/Desktop"
dirList=os.listdir(path)
for i, fname in enumerate(dirList):
print "%d) %s" % (i + 1, fname)
while True:
try:
selectedInt = int(raw_input("Select a file above: "))
selected = dirList[selectedInt - 1]
break
except Exception:
print "Error: Please enter a number between 1 and %d" % len(dirList)
您可以尝试以下操作:
这应该能达到目的:)
但是,请注意,没有进行错误更正。您应该捕捉输入不是整数的情况。在
您应该对列表使用枚举,然后处理输入错误。理想情况下,这将是一个函数,而不是执行
break
操作,而是返回选定的文件。在相关问题 更多 >
编程相关推荐