Skip to main content
 首页 » 编程设计

递归打印目录的Python代码

2025年05月04日11TianFang

我有以下代码,但它会遍历它找到的第一个目录并停止。 我觉得我有递归函数,它也应该给其他目录。 谁能指出这段代码有什么问题。

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) 

输出:

-- 1.txt 
-- 2.txt 
-- 3.txt 
-- blue 
---- 33.txt 
---- 45.txt 
---- 56.txt 
---- Tere 

“blue”和“tere”是目录。 “HELLO”文件夹中还有更多目录未打印。

请您参考如下方法:

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

import os 
 
path = r'path\to\root\dir' 
for root, dirs, files in os.walk(path): 
    # Access subdirs and files 

另一个注意事项:

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

    print '{} {}'.format(no*'-', item)`  
    

    代替

    print no * "-" + " " + item