尝试获取用户输入以从列表中选择目录时遇到问题
def listPath():
p = list(os.listdir(work_path,))
for dirs in enumerate(p,1):
i = print(dirs, sep ="\n")
这将输出当前文件夹中目录的编号列表:
(1, 'Folder 1')
(2, 'Folder 2')
(3, 'Folder 3')
我想允许用户从此列表中选择一个目录,然后移至该目录。 但是我迷路了。
任何帮助将不胜感激。
答案 0 :(得分:0)
您可以使用
answer = input("Which folder do you want,enter a number?")
询问用户。然后使用他输入的内容。
print("You selected folder: {}".format(p[int(answer)-1]))
减1,因为您在枚举中加了1。
答案 1 :(得分:0)
您的解决方案可能是这样:
def listPath():
path = 'your path'
for x in os.listdir(path):
print(x) # this prints the folders or file that are inside your path directory
要获得文件或文件夹的完整路径的输出并选择文件夹,则可以
import os
def listPath():
list_path = []
numbered = 1
path = 'your path'
for x in os.listdir(path):
acutal_path = str(numbered) + ' ' + path + os.sep + x #This variable stores full path for your all sub directory
list_path.append(actual_path)
print(str(numbered) + actual_path)
answer = input("Which folder do you want,enter a number?") # Ask user to enter to which number they want to enter
for y in list_path:
if answer in y:
print('You have selected {}'.format(list_path[int(answer)])
os.chdir(actual_path[int(answer)]) # Change you to the selected directory by the user.