1
votes

How do I generate a list of dynamic menu items based on the number of files present in a folder?

The current code retrieves the filenames in the folder, but it needs to generate menu options.

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

Desired functionality:

"Select file to manipulate: 
[1] test.csv
[2] test2.csv
[3] test3.csv"

It should then take the raw_input for 1, 2 or 3 and select corresponding f in file_names. I will then do folder + ans to create a full path path/folder/to/read/test.csv.

Static example:

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
2
"it needs to generate menu options" - all you need to do is print the items, then take a number from the user and use it as a list index to get the selected file name (keeping in mind that python lists start with index 0). That's absolutely trivial, if you're unable to code that on your own you should read a few tutorials covering the python basics.l4mpi

2 Answers

2
votes

Made my own solution:

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
0
votes

In 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)
    break