如何遍历python中的目录?

How to traverse a directory in python?

我有这个代码:

def traverse_dir(fd):      

    for dir_path,subpaths,files in os.walk(fd): 
        print dir_path,subpaths
        for file in files:
            print "file:%s"  %file

def traverse_func(arg,dirname,files):   

    print dirname
    for file in files:
            print "file:%s"  %file

os.path.walk(r".",traverse_func,())

我应该使用 os.walk() 还是 os.path.walk(),为什么?

或者有其他更好的方法吗?

这取决于您使用的 Python 版本。在 Python 2 中有 os.path.walk() (docs) but it has been deprecated and replaced with os.walk() (docs) 在 Python 3.

Python(x,y) 您声称在评论中使用,seems to be based on Python 2

os.walk(dir) returns 一个元组必须解包。

for a, b, c in os.walk(dir):
  print("{} contains the directories {} and the files {}".format(a, b, c))

真的很简单

对于 Python 3.6+ 你可以稍微简化一下:

for a, b, c in os.walk(dir):
  print(f"{a} contains the directories {b} and the files {c}")

os.path.walk() function is deprecated and is no longer available in Python 3. For that reason you should prefer os.walk().

通过将 followlinks 参数设置为 True

os.walk() 也可以跟随符号 link 到目录。要对 os.path.walk() 执行相同操作,您必须专门检查每个目录是否是 sym link,并自行解决。 os.walk() 还有几个其他可能有用的选项,所以总的来说,选择它而不是 os.path.walk()

你可以用同样的方法实现。

os.listdir() + 递归

def traverseFolder(ROOT):

    for entry in os.listdir(ROOT):
        path = os.path.join(ROOT,entry)
        if os.path.isdir(path):
            traverseFolder(path)  #call to process sub-directory
        else:
            fhand = open(path,'r')
            data = fhand.read()
            ......


traverseFolder('path/someFolder')