用于递归打印目录的Python代码

Vin*_*d K 1 python directory macos

我有以下代码,但它遍历它找到并停止的第一个目录.我觉得我有递归功能,应该给其他目录.任何人都可以指出这个代码有什么问题.

def func(path,no):
    no=no+2
    for item in os.listdir(path):
        if os.path.isfile(path+"\\"+item):
            print no * "-" + " " + item
        if os.path.isdir(path+"\\"+item):
            path=path + "\\" + item
            print no * "-" + " " + item
            func(path,no)


path="D:\\Hello"
no=0
func(pah,no)
Run Code Online (Sandbox Code Playgroud)

输出:

-- 1.txt
-- 2.txt
-- 3.txt
-- blue
---- 33.txt
---- 45.txt
---- 56.txt
---- Tere
Run Code Online (Sandbox Code Playgroud)

"blue"和"tere"是目录."HELLO"文件夹中有更多目录未打印.

Ste*_*ima 5

要递归遍历目录,请使用os.walk

import os

path = r'path\to\root\dir'
for root, dirs, files in os.walk(path):
    # Access subdirs and files
Run Code Online (Sandbox Code Playgroud)

另一个注意事项:

  1. 要将路径的某些部分连接在一起,请使用os.path.join.而不是 path+"\\"+item你可以使用os.path.join(path, item).这将适用于所有平台,您不必考虑转义斜杠等.
  2. 打印值的更好方法是使用该format方法.在你的情况下你可以写

    print '{} {}'.format(no*'-', item)` 
    
    Run Code Online (Sandbox Code Playgroud)

    代替

    print no * "-" + " " + item
    
    Run Code Online (Sandbox Code Playgroud)