遍历目录树的方式有哪几种?

发布于 2024-07-12 22:02:41 字数 102 浏览 8 评论 0原文

如何用您最喜欢的语言遍历目录树?

要在不同操作系统中遍历目录树,您需要了解什么? 在不同的文件系统上?

您最喜欢的帮助遍历目录树的库/模块是什么?

How do you traverse a directory tree in your favorite language?

What do you need to know to traverse a directory tree in different operating systems? On different filesystems?

What's your favorite library/module for aiding in traversing a directory tree?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

南城旧梦 2024-07-19 22:02:41

在 Python 中:

如果您正在寻找快速、干净且可移植的解决方案,请尝试:

import os
base_dir = '.'

def foo(arg, curr_dir, files):
  print curr_dir
  print files

os.path.walk(base_dir, foo, None)

请注意,您可以修改 foo 来执行其他操作,而不仅仅是打印名称。 此外,如果您有兴趣迁移到 Python 3.0,则必须使用 os.walk()。

In Python:

If you're looking for a quick, clean, and portable solution try:

import os
base_dir = '.'

def foo(arg, curr_dir, files):
  print curr_dir
  print files

os.path.walk(base_dir, foo, None)

Note that you can modify foo to do something else instead of just printing the names. Furthermore, if you're interested in migrating to Python 3.0, you will have to use os.walk() instead.

枯叶蝶 2024-07-19 22:02:41

Java中:

递归在这里很有用。 以下是一段已在互联网上流传多年的 Java 代码片段。 不确定谁应该为此功劳。

// Process all files and directories under dir

    public static void visitAllDirsAndFiles(File dir) {

        process(dir);  //do something useful with the file or dir

        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i=0; i<children.length; i++) {
                visitAllDirsAndFiles(new File(dir, children[i]));
            }
        }
    }

In Java:

Recursion is useful here. Following is a Java code snippet that's been all over the Internet for ages. Not sure who deserves the credit for it.

// Process all files and directories under dir

    public static void visitAllDirsAndFiles(File dir) {

        process(dir);  //do something useful with the file or dir

        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i=0; i<children.length; i++) {
                visitAllDirsAndFiles(new File(dir, children[i]));
            }
        }
    }
漆黑的白昼 2024-07-19 22:02:41

bash:(

#!/bin/bash

function walk_tree {
      echo "Directory: $1"
      local directory="$1"
      local i
      for i in "$directory"/*; 
      do
      echo "File: $i"
        if [ "$i" = . -o "$i" = .. ]; then 
            continue
        elif [ -d "$i" ]; then  # Process directory and / or walk-down into directory
            # add command here to process all files in directory (i.e. ls -l "$i/"*)
            walk_tree "$i"      # DO NOT COMMENT OUT THIS LINE!!
        else
            continue    # replace continue to process individual file (i.e. echo "$i")
        fi
      done
}

walk_tree $HOME

改编自http://ubuntuforums.org/showthread.php?t=886272 评论 #4)

bash:

#!/bin/bash

function walk_tree {
      echo "Directory: $1"
      local directory="$1"
      local i
      for i in "$directory"/*; 
      do
      echo "File: $i"
        if [ "$i" = . -o "$i" = .. ]; then 
            continue
        elif [ -d "$i" ]; then  # Process directory and / or walk-down into directory
            # add command here to process all files in directory (i.e. ls -l "$i/"*)
            walk_tree "$i"      # DO NOT COMMENT OUT THIS LINE!!
        else
            continue    # replace continue to process individual file (i.e. echo "$i")
        fi
      done
}

walk_tree $HOME

(adapted from http://ubuntuforums.org/showthread.php?t=886272 Comment #4)

小帐篷 2024-07-19 22:02:41

C#中:

Stack<DirectoryInfo> dirs = new Stack<DirectoryInfo>();

dirs.Push(new DirectoryInfo("C:\\"));

while (dirs.Count > 0) {
    DirectoryInfo current = dirs.Pop();

    // Do something with 'current' (if you want)

    Array.ForEach(current.GetFiles(), delegate(FileInfo f)
    {
        // Do something with 'f'
    });

    Array.ForEach(current.GetDirectories(), delegate(DirectoryInfo d)
    {
        dirs.Push(d);
    });
}

In C#:

Stack<DirectoryInfo> dirs = new Stack<DirectoryInfo>();

dirs.Push(new DirectoryInfo("C:\\"));

while (dirs.Count > 0) {
    DirectoryInfo current = dirs.Pop();

    // Do something with 'current' (if you want)

    Array.ForEach(current.GetFiles(), delegate(FileInfo f)
    {
        // Do something with 'f'
    });

    Array.ForEach(current.GetDirectories(), delegate(DirectoryInfo d)
    {
        dirs.Push(d);
    });
}
清泪尽 2024-07-19 22:02:41

嗯,C# 带有一定程度的递归......

public static List<string> CrawlPath(string path, bool IncludeSubFolders)
{
    List<string> fileList = new List<string>();
    try
    {
        Stack<string> filez = new Stack<string>(Directory.GetFiles(path));
        while (filez.Count > 0)
        {
            fileList.Add(filez.Pop());
        }

        if (IncludeSubFolders)
        {
            filez = new Stack<string>(Directory.GetDirectories(path));
            while (filez.Count > 0)
            {
                string curDir = filez.Pop();
                fileList.AddRange(CrawlPath(curDir, IncludeSubFolders));
            }
        }
     }
     catch (System.Exception err)
     {
         Console.WriteLine("Error: " + err.Message);
     }
     return fileList;
  }

mmmm, C# with a dose of recursion.....

public static List<string> CrawlPath(string path, bool IncludeSubFolders)
{
    List<string> fileList = new List<string>();
    try
    {
        Stack<string> filez = new Stack<string>(Directory.GetFiles(path));
        while (filez.Count > 0)
        {
            fileList.Add(filez.Pop());
        }

        if (IncludeSubFolders)
        {
            filez = new Stack<string>(Directory.GetDirectories(path));
            while (filez.Count > 0)
            {
                string curDir = filez.Pop();
                fileList.AddRange(CrawlPath(curDir, IncludeSubFolders));
            }
        }
     }
     catch (System.Exception err)
     {
         Console.WriteLine("Error: " + err.Message);
     }
     return fileList;
  }
梦屿孤独相伴 2024-07-19 22:02:41

C++

#include <utility>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>

#define foreach BOOST_FOREACH
namespace fs = boost::filesystem;

fs::recursive_directory_iterator it(top), eod;
foreach (fs::path const & p, std::make_pair(it, eod)) {
    if (is_directory(p)) {
        ...
    } else if (is_regular_file(p)) {
        ...
    } else if (is_symlink(p)) {
        ...
    }
}

C++

#include <utility>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>

#define foreach BOOST_FOREACH
namespace fs = boost::filesystem;

fs::recursive_directory_iterator it(top), eod;
foreach (fs::path const & p, std::make_pair(it, eod)) {
    if (is_directory(p)) {
        ...
    } else if (is_regular_file(p)) {
        ...
    } else if (is_symlink(p)) {
        ...
    }
}
说谎友 2024-07-19 22:02:41

在带有 GNU 工具的 Linux 上

find -print0 | xargs -0 md5sum

find -print0 | xargs -0 -iASD echo 'this file "ASD" should be dealt with lile this (ASD)'

On Linux with GNU tools

find -print0 | xargs -0 md5sum

or

find -print0 | xargs -0 -iASD echo 'this file "ASD" should be dealt with lile this (ASD)'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文