【问题标题】:traverse directory structure in python recursively without os.walk在没有os.walk的情况下递归遍历python中的目录结构
【发布时间】:2017-05-31 08:11:57
【问题描述】:

我正在尝试编写一个python2函数,它将递归遍历给定目录的整个目录结构,并打印出结果。

全部不用os.walk

这是我目前得到的:

test_path = "/home/user/Developer/test"

def scanning(sPath):
    output = os.path.join(sPath, 'output')
    if os.path.exists(output):
        with open(output) as file1:
            for line in file1:
                if line.startswith('Final value:'):
                    print line
    else:
        for name in os.listdir(sPath):
            path = os.path.join(sPath, name)
            if os.path.isdir(path):
                print "'", name, "'"
                print_directory_contents(path)

scanning(test_path)

这是我目前得到的,脚本没有进入新文件夹:

' test2'
'new_folder'

问题在于它不会比一个目录更进一步。我还希望能够直观地指示什么是目录,什么是文件

【问题讨论】:

  • 不幸的是,os.walk 即使在 python 3 下仍然是最可行的文件夹列表机制。
  • 我更愿意使用它!但是有人要求我不要使用 os.walk :(

标签: python python-2.7 for-loop recursion


【解决方案1】:

试试这个:

import os

test_path = "YOUR_DIRECTORY"

def print_directory_contents(dir_path):
    for child in os.listdir(dir_path):
        path = os.path.join(dir_path, child)
        if os.path.isdir(path):
            print("FOLDER: " + "\t" + path)
            print_directory_contents(path)

        else:
            print("FILE: " + "\t" + path)

print_directory_contents(test_path)

我在 Windows 上工作,验证是否仍在 unix 上工作。 改编自: http://codegists.com/snippet/python/print_directory_contentspy_skobnikoff_python

【讨论】:

  • 我可以确认我使用的是 linux :)
【解决方案2】:

用递归试试这个 它非常简单,代码更少

import os

def getFiles(path="/var/log", files=[]):
    if os.path.isfile(path):
        return files.append(path)
    for item in os.listdir(path):
        item = os.path.join(path, item)
        if os.path.isfile(item):
            files.append(item)
        else:
            files = getFiles(item, files)
    return files  



for f in getFiles("/home/afouda/test", []):
    print(f)

【讨论】:

    【解决方案3】:

    尝试使用递归函数,

    def lastline(fil):
        with open(fil) as f:
            for li in f.readlines():
                if li.startswith("Final Value:"):
                    print(li)
    
    ## If it still doesnt work try putting 'dirs=[]' here
    def lookforfiles(basepath):
        contents = os.listdir(basepath)
    
        dirs = []
        i = 0
    
        while i <= len(contents):
            i += 1
    
            for n in contents:
                f = os.path.join(basepath, n)
    
                if os.path.isfile(f):
                    lastline(f)
                    print("\n\nfile %s" % n)
                elif os.path.isdir(f):
                    print("Adding dir")
                    if f in dirs:
                        pass
                    else:
                        dirs.append(f)
    
        else:   
            for x in dirs:
                print("dir %s" % x)
                lookforfiles(x)
    

    很抱歉,如果这不完全符合您的示例,但我很难理解您要做什么。

    【讨论】:

    • lookforfiles 函数中的 f 显示为未解析的引用,我做错了吗?
    • 我自己发现了。我的大脑添加了我的手没有得到的代码。刚刚编辑了哈哈。
    • 哈哈不用担心,每个人都会遇到!尽管您的代码出现错误:TypeError: coercing to Unicode: need string or buffer, NoneType found in the lookforfiles function on line: contents = os.listdir(basepath)
    • 确保目录正确,并在控制台中使用任何目录尝试 os.listdir。只是为了让你可以看到输出。
    • 好吧,这对我有用,只是要注意,在读取文件时,有时它无法分辨类型,如果无法读取文本,则会抛出异常。
    【解决方案4】:

    此问题与Print out the whole directory tree 重复。

    TL;TR:使用os.listdir

    【讨论】:

      猜你喜欢
      • 2013-06-01
      • 2023-01-09
      • 1970-01-01
      • 2014-08-08
      • 2015-12-18
      • 2014-12-07
      • 1970-01-01
      • 1970-01-01
      • 2013-01-23
      相关资源
      最近更新 更多