【问题标题】:python directory recursive traversal programpython目录递归遍历程序
【发布时间】:2013-01-23 15:30:24
【问题描述】:

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

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(".", "")

【问题讨论】:

  • 我刚刚在 ubuntu 12.04 上使用 python 2.7 对其进行了测试,并且可以正常工作。不知道为什么它不适合你。
  • @placeybordeaux im on os x...这可能是个问题吗?
  • 附带说明:不要在 Python 中的 if 条件等周围加上括号;这很不和谐,并引起了人们对“他在这里做一些需要括号的复杂事情吗?”的关注。而不是实际情况。

标签: python recursion directory


【解决方案1】:

从那里看到os.walk

这个例子显示了起始目录下每个目录中非目录文件占用的字节数,除了它不查看任何 CVS 子目录下:

import os
from os.path import join, getsize
for root, dirs, files in os.walk('python/Lib/email'):
    print root, "consumes",
    print sum(getsize(join(root, name)) for name in files),
    print "bytes in", len(files), "non-directory files"
    if 'CVS' in dirs:
        dirs.remove('CVS')  # don't visit CVS directories

【讨论】:

  • 谢谢你的回答,我不知道os walk,但它似乎很容易实现。
【解决方案2】:

问题在于您没有检查正确的内容。 file 只是文件名,而不是路径名。这就是为什么你需要os.path.join(dir, file),在下一行,对吧?所以你在isdir 电话中也需要它。但你只是传递file

所以,与其问“.foo/bar/baz 是一个目录吗?”你只是在问“baz 是一个目录吗?”如您所料,它将baz 解释为./baz。而且,由于(可能)没有“./baz”,你会返回 False。

所以,改变这个:

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)

话虽如此,按照 sotapme 的建议使用 os.walk 比尝试自己构建更简单。

【讨论】:

    猜你喜欢
    • 2019-06-24
    • 1970-01-01
    • 2013-06-01
    • 2023-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-01
    相关资源
    最近更新 更多