从os.listdir创建动态菜单

时间:2015-06-19 10:24:03

标签: python python-2.7

如何根据文件夹中存在的文件数生成动态菜单项列表?

当前代码检索文件夹中的文件名,但需要生成菜单选项。

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 123,并在f中选择相应的file_names。然后,我会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

1 个答案:

答案 0 :(得分:1)

制定了我自己的解决方案:

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
相关问题