如何用您喜欢的语言遍历目录树?
在不同操作系统中遍历目录树需要了解什么?在不同的文件系统上?
您最喜欢的库/模块是什么帮助遍历目录树?
答案 0 :(得分:7)
在 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()。
答案 1 :(得分:6)
在 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]));
}
}
}
答案 2 :(得分:4)
击:
#!/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
答案 3 :(得分:3)
在 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);
});
}
答案 4 :(得分:3)
<强> 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)) {
...
}
}
答案 5 :(得分:2)
在使用GNU工具的Linux上
find -print0 | xargs -0 md5sum
或
find -print0 | xargs -0 -iASD echo 'this file "ASD" should be dealt with lile this (ASD)'
答案 6 :(得分:1)
mmmm,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;
}