0

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

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\\*.*'
4

2 回答 2

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)
于 2013-03-15T19:41:38.313 回答
1

您可能更喜欢使用更 Pythonic 的os.walk。它将递归变成一个简单易懂的循环,并为您管理遍历目录。

于 2013-03-15T19:15:25.177 回答