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

Python 如何递归打印每个文件或文件夹的路径名,python,python-3.x,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 re

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

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\\*.*'
遍历(“测试”,0)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
遍历(“测试”,0)
文件“C:\Users\Phuchu\Desktop\Python\homework8.py”,第65行,在traverse中
对于os.listdir(路径)中的项:
FileNotFoundError:[WinError 3]系统找不到指定的路径:“测试\\*.*”
您可能更喜欢使用,它更像是python。它将把递归变成一个简单易懂的循环,并为您管理到目录中的遍历。

使用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)

您当前的目录是什么?
test
是它的一个子目录吗?你不应该用
'*.*.'
作为
d
的参数来调用你的函数。是的。test也有几个文件夹在里面