在Python中使用函数列出文件夹名称

时间:2019-04-21 03:09:00

标签: python python-3.x function

我创建了一个程序,该程序创建了一个列出内容的函数 任意数量的文件夹。 函数的参数列表将是程序中文件夹名称的列表。 该函数的返回值将是一个Dictionary,其中的键是文件夹,而值是该文件夹内容的列表。我已经创建了代码,但仍然不断出错。

我已经尝试过使用以前编码并可以正常工作的功能,但是我无法使它适用于此特定程序。

import os
folder_path = "C:\\Users\\Anonymous\\Desktop\\Test"
# function header
# def function_name(parameter_list)
def expand_folders(folder_names):
# declare an empty dictionary
    result_dict= {}
# for each folder name
for name in folder_names:
# get the full path of folder
    folder = os.path.join(folder_path, name)
# store name as key and the list of files as value
# after this line the dictionary will have one key-value pair
    result_dict[name] = os.listdir(folder)
return result_dict



print("Folders List")
print(os.listdir(folder_path))
print()
# an empty list to keep selected folder names
folder_names = []
while True:
# get folder name
    name = input("Select a folder to expand: ")
    if(name == 'Q' or name == 'q'):
        break
folder_names.append(name)
result_dict = expand_folders(folder_names)
print(result_dict)

预期结果将使程序要求选择一个文件夹,例如 文件夹列表:[1,2,3,4,5]

选择要列出的文件夹:1 选择要列出的文件夹:3 选择要列出的文件夹:Q {'1':['file11.txt'],'3':['file13.txt']}

2 个答案:

答案 0 :(得分:3)

有几处错误:

  1. 您的缩进不一致。正如@Smart Pointer提到的那样,缩进在Python中非常重要,因为缩进是解释器知道特定循环/函数中包含哪些代码的唯一方法。

  2. folder = os.path.join(folder_path, name)将导致folder变量设置为folder_path,加上folder_names中的最后一个文件夹名称。

这是修改后的代码:

import os
folder_path = "C:\\"
# function header
# def function_name(parameter_list)
def expand_folders(folder_names):
    # declare an empty dictionary
    result_dict= {}
    # for each folder name
    folder = folder_path
    for name in folder_names:
        # get the full path of folder
        folder = os.path.join(folder, name)
    # store name as key and the list of files as value
    # after this line the dictionary will have one key-value pair
    result_dict[name] = os.listdir(folder)
    return result_dict



print("Folders List")
print(os.listdir(folder_path))
print()
# an empty list to keep selected folder names
folder_names = []
while True:
    # get folder name
    name = input("Select a folder to expand: ")
    if(name == 'Q' or name == 'q'):
        break
    folder_names.append(name)
    result_dict = expand_folders(folder_names)
    print(result_dict)

答案 1 :(得分:0)

您的代码很好,只需修复缩进(在Python中这确实很重要):

def expand_folders(folder_names):
    result_dict= {}
    for name in folder_names:
        folder = os.path.join(folder_path, name)
        result_dict[name] = os.listdir(folder)
    return result_dict