Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.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 只能遍历给定目录的第一个子目录,但不能遍历所有子目录_Python - Fatal编程技术网

Python 只能遍历给定目录的第一个子目录,但不能遍历所有子目录

Python 只能遍历给定目录的第一个子目录,但不能遍历所有子目录,python,Python,编写一个程序,不使用“os.walk”遍历给定目录的所有目录和其中的文件,但我只能遍历给定目录的第一个子目录,而不能遍历全部目录 import os sub_dir = [] fi = [] def print_directory_contents(sPath): di = os.listdir(sPath) for y in di: if "." in y: fi.append(y) else:

编写一个程序,不使用“os.walk”遍历给定目录的所有目录和其中的文件,但我只能遍历给定目录的第一个子目录,而不能遍历全部目录

import os

sub_dir = []

fi = []

def print_directory_contents(sPath):

    di = os.listdir(sPath)
    for y in di:
        if "." in y:
            fi.append(y)
        else:
            sub_dir.append(y)

    print("path : ", sPath)
    print("dir : ", sub_dir)
    print("file : ", fi)
    print("--------------------------------\n")
    sub_dir.clear()
    fi.clear()
    # print(di)

    print(di)
    for x in di:
        print(di)
        if os.path.isdir('{}/{}'.format(sPath, x)):
            os.chdir('{}/{}'.format(sPath, x))
            new_spath = os.getcwd()
            print_directory_contents(new_spath)

check_dir = input()

print_directory_contents(check_dir)

递归调用函数,如下所示:

import os

def print_directory_contents(sPath):
    print sPath
    for dir in os.listdir(sPath):
        if os.path.isdir(os.path.join(sPath, dir)):
            print_directory_contents(os.path.join(sPath, dir))

你在重新发明,很糟糕。你的问题只是代码…再次检查更改。感谢@SergeBallesta问题已经解决,现在问题可以解决:-)我知道我可以用os.walk来完成,但我有一个挑战,不使用“os.walk”来完成,然后调用
print\u directory\u contents(sPath)
递归地将sPath作为子目录。即使在使用“打印目录”内容(sPath)编辑后,它也只完全遍历给定目录的第一个子目录。谢谢,这个解决方案解决了我的问题