如何根据文件夹中的文件数量生成动态菜单项列表?
当前代码检索文件夹中的文件名,但需要生成菜单选项。
from os import listdir
from os.path import isfile, join
folder = "path/folder/to/read/"
file_names = [fn for fn in listdir(folder) if isfile(join(folder,fn))]
print "Select file to manipulate:\n"
for f in file_names: print #Add iterable menu items here somehow期望的功能:
"Select file to manipulate:
[1] test.csv
[2] test2.csv
[3] test3.csv"然后,它应该将raw_input用于1、2或3,并在file_names中选择相应的f。然后我将执行folder + ans来创建一个完整的路径path/folder/to/read/test.csv。
静态示例:
while ans:
print ("""
[1]. Option 1
[2]. Option 2
[3]. Option 3
""")
ans = raw_input("Select action: ")
if ans == "1":
#do something
if ans == "2":
#do something else
if ans == "3":
#do something different发布于 2015-06-19 17:23:04
做了我自己的解决方案
folder = "path/folder/to/read/"
file_names = [fn for fn in listdir(folder) if isfile(join(folder,fn))]
count = -1
for f in file_names:
count = count + 1
print "[%s] " % count + f
while True:
ans_file = input("Select file: ")
if ans_file > count:
print "Wrong selection."
continue
path = folder + file_names[ans_file]
print "Selected file: %s " % path
break发布于 2022-01-25 21:07:57
在Python3中:
from os import listdir
from os.path import isfile, join
folder = "examples/"
file_names = [fn for fn in listdir(folder) if isfile(join(folder,fn))]
count = -1
for f in file_names:
count = count + 1
print ("[%s] " % count + f)
while True:
ans_file = int(input("Select file: "))
if (ans_file > count):
print ("Wrong selection.")
continue
path = folder + file_names[ans_file]
print ("Selected file: %s " % path)
breakhttps://stackoverflow.com/questions/30935781
复制相似问题