Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python目录递归遍历程序_Python_Recursion_Directory - Fatal编程技术网

python目录递归遍历程序

python目录递归遍历程序,python,recursion,directory,Python,Recursion,Directory,我的程序不相信文件夹是目录,假设它们是文件,因此递归将文件夹打印为文件,然后由于没有文件夹等待遍历,程序完成 import os import sys class DRT: def dirTrav(self, dir, buff): newdir = [] for file in os.listdir(dir): print(file) if(os.path.isdir(file)):

我的程序不相信文件夹是目录,假设它们是文件,因此递归将文件夹打印为文件,然后由于没有文件夹等待遍历,程序完成

import os
import sys
class DRT:
    def dirTrav(self, dir, buff):
        newdir = []
        for file in os.listdir(dir):
            print(file)
            if(os.path.isdir(file)):
                newdir.append(os.path.join(dir, file))
        for f in newdir:
            print("dir: " + f)
            self.dirTrav(f, "")
dr = DRT()
dr.dirTrav(".", "")
从那里可以看到:

此示例显示起始目录下每个目录中的非目录文件占用的字节数,但不在任何CVS子目录下查找:


问题是你没有检查正确的东西<代码>文件只是文件名,而不是路径名。这就是为什么在下一行需要
os.path.join(dir,file)
,对吗?因此,在
isdir
调用中也需要它。但您只是传递
文件

因此,你不是问“is
.foo/bar/baz
目录吗?”而是问“is
baz
目录吗?”正如你所料,它只是将
baz
解释为
/baz
。而且,因为(可能)没有“
/baz
”,所以返回False

因此,改变这一点:

if(os.path.isdir(file)):
    newdir.append(os.path.join(dir, file))
致:


综上所述,按照sotapme的建议使用
os.walk
比自己构建要简单。

我刚刚用python 2.7在Ubuntu12.04上对它进行了测试,效果很好。不知道为什么不适合你。@placeybordeaux操作系统x上的im。。。这可能是个问题吗?作为旁注:在Python中,不要在
if
条件等周围加括号;这很刺耳,让人注意到“他在做一些需要括号的复杂事情吗?”而不是实际情况。谢谢你的回答,我不知道os walk,但它似乎很容易实现。
if(os.path.isdir(file)):
    newdir.append(os.path.join(dir, file))
path = os.path.join(dir, file)
if os.path.isdir(path):
    newdir.append(path)