Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.7 使用os.listdir()创建文件列表_Python 2.7 - Fatal编程技术网

Python 2.7 使用os.listdir()创建文件列表

Python 2.7 使用os.listdir()创建文件列表,python-2.7,Python 2.7,我知道我可以使用os.listdir(path)创建给定目录内部的列表,但是如果我想知道目录内部的内容,而这些目录本身在“path”中指定的目录中,该怎么办 我有一个主目录,包含25个目录;每个目录都包含30多个目录,每个目录中都有3-10个文件需要读入我的脚本。到目前为止,我已经尝试创建列表列表来记录所有目录,但它很快就失控了: list = os.listdir(path) # Path to the main directory newList = [] for i in range(

我知道我可以使用os.listdir(path)创建给定目录内部的列表,但是如果我想知道目录内部的内容,而这些目录本身在“path”中指定的目录中,该怎么办

我有一个主目录,包含25个目录;每个目录都包含30多个目录,每个目录中都有3-10个文件需要读入我的脚本。到目前为止,我已经尝试创建列表列表来记录所有目录,但它很快就失控了:

list = os.listdir(path)   # Path to the main directory
newList = []
for i in range(len(list)):
    newList.append(path + list[i])   # I modify the path so the next os.listdir command
                                     # finds the correct directory

list1 = []
for i in range(len(newList)):
    list1.append(os.listdir(newList[i]))    # Create a new list of lists for first set
                                            # of interior directories
list2 = []
for i in range(len(list1)):
    for j in range(len(list1[i])):
        list2.append(os.listdir(list1[i][j]))   # I'm encountering an error here

有没有一个命令可以帮我完成所有这些工作?我正在寻找的东西,给定一个路径,将返回其中所有目录的所有内容。任何建议都将不胜感激。

您已经看过
os.walk()
了吗?您还应该使用
os.path.join()
而不是串联路径。另外,直接循环列表,而不是使用循环范围()然后索引到原始列表。os.walk()处理了它,谢谢!