如何递归地打印每个文件或文件夹的路径名

时间:2013-03-15 18:50:51

标签: python python-3.x

这是我的代码和错误!请给我一个提示

import os
def traverse(path, d):
    for item in os.listdir(path):
        item = os.path.join(path, d)
        try:
            traverse(path,d)
        except:
            print (path)

我的错误:

traverse ("test",0)
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    traverse ("test",0)
  File "C:\Users\Phuchu\Desktop\Python\homework8.py", line 65, in traverse
    for item in os.listdir(path):
FileNotFoundError: [WinError 3] The system cannot find the path specified: 'test\\*.*'

2 个答案:

答案 0 :(得分:1)

您可能更喜欢使用os.walk,这是更加pythonic。它会将递归转换为一个易于理解的循环,并将为您管理遍历目录。

答案 1 :(得分:1)

使用os.walk

import os

def traverse(current_dir):
    for root, dirs, files in os.walk(current_dir):
        #print all files  recursively
        for file in files:
             print os.path.join(root,file)
         #print all folders recursively
        for dir in dirs:
             print os.path.join(root,dir)