php函数scandir_PHP: scandir - Manual

Scandir on steroids:

For when you want to filter your file list, or only want to list so many levels of subdirectories...

//  start search in $path (defaults to current working directory)

//  return $types:  2 => files; 1 => directories; 3 => both;

//  $levels: 1 => look in the $path only; 2 => $path and all children;

//          3 => $path, children, grandchildren; 0 => $path and all subdirectories;

//          less than 0 => complement of -$levels, OR everything starting -$levels down

//                e.g. -1 => everthing except $path; -2 => all descendants except $path + children

//  Remaining argument(s) is(are) a filter array(list) of regular expressions which operate on the full path.

//    First character (before the '/' of the regExp) '-' => NOT.

//    First character (after a possible '-') 'd' => apply to directory name

//    The filters may be passed in as an array of strings or as a list of strings

//  Note that output directories are prefixed with a '*' (done in the line above the return)$dS=DIRECTORY_SEPARATOR;

if (!($path=realpath($path?$path:getcwd()))) return array();// bad path

// next line rids terminating \ on drives (works since c: == c:\ on PHP).  OK in *nix?if (substr($path,-1)==$dS)$path=substr($path,0,-1);

if (is_null($types))$types=2;

if (is_null($levels))$levels=1;

if (is_null($aFilter))$aFilter=array();// last argument may be passed as a list or as an array$aFilter=array_slice(func_get_args(),3);

if ($aFilter&&gettype($aFilter[0])=="array")$aFilter=$aFilter[0];$adFilter= array();// now move directory filters to separate array:foreach ($aFilteras$i=>$filter)// for each directory filter...if (($pos=stripos("$filter","d")) &&$pos<3) {// next line eliminates the 'd'$adFilter[] =substr($filter,0,$pos-1) .substr($filter,$pos);

unset($aFilter[$i]); }$aFilter=array_merge($aFilter);// reset indeces$aRes= array();// results, $aAcc is an Accumulator$aDir= array($path);// dirs to checkfor ($i=$levels>0?$levels++:-1;($aAcc=array())||$i--&&$aDir;$aDir=$aAcc)

while ($dir=array_shift($aDir))

foreach (scandir($dir) as$fileOrDir)

if ($fileOrDir!="."&&$fileOrDir!="..") {

if ($dirP=is_dir($rp="$dir$dS$fileOrDir"))

if (pathFilter("$rp$dS",$adFilter))$aAcc[] =$rp;

if ($i

if (pathFilter($rp,$aFilter))$aRes[] = ($dirP?"*":"") .$rp; }

return$aRes;

}?>

example usage:

define("_",NULL);// this will find all non .jpg, non .Thumbs.db files under c:\Photo$aFiles=dirList('c:\Photo',_,0,'-/\.jpg$/i','-/\\\\Thumbs.db$/');$aFiles=dirList();// find the files in the current directory

// next lines will find .jpg files in non Photo(s) subdirectories, excluding Temporary Internet Filesset_time_limit(60);// iterating from the top level can take a while$aFiles=dirList("c:\\",_,0,'/\.jpg$/i','-d/\\\\Photos?$/i','-d/Temporary Internet/i');?>

Note that this function will consume a lot of time if scanning large

directory structures (which is the reason for the '[-]d/.../' filters).

Csaba Gabor from Vienna

这是一段 Python 代码,用于遍历指定路径中的所有目录,并可限制最大深度。以下是每一行代码的解释: 1. `import math import operator import os from pathlib import Path` :这一行代码导入了 `math`、`operator`、`os` 和 `Path` 模块,使得我们可以使用这些模块提供的函数和类。 2. `def walk_to_find_directories(` :这一行开始定义一个名为 `walk_to_find_directories` 的函数,并传入三个参数。 3. `path: str,` :指定路径的字符串类型参数,即要遍历的路径。 4. `depth: int = math.inf,` :深度的整数类型参数,用于控制遍历的最大深度,默认值为正无穷(即不限制深度)。 5. `including_source_directoriy: bool = False` :一个布尔类型参数,指示是否包括源目录(即传入的路径本身),默认值为 `False`。 6. `):` :函数定义的结尾,表示函数开始执行。 7. `if including_source_directoriy:` :如果 `including_source_directoriy` 为 `True`,则执行以下代码。 8. `yield Path(path)` :通过 `yield` 关键字返回 `path` 参数构建的 `Path` 对象作为生成器的值。 9. `depth -= 1` :将 `depth` 参数减 1,为后续的递归遍历做准备。 10. `with os.scandir(path) as p:` :使用 `with` 语句创建一个上下文管理器,同时遍历指定路径下的所有文件和目录,并赋值给 `p`。 11. `p = list(p)` :将 `p` 转化为一个列表。 12. `p.sort(key=operator.attrgetter("name"))` :按照文件或目录名称进行排序,使用 `operator.attrgetter` 函数实现属性获取。 13. `for entry in p:` :循环读取列表 `p` 中的每一个元素,即遍历文件和目录。 14. `if entry.is_dir():` :如果当前元素是目录。 15. `yield Path(entry.path)` :将当前元素创建的 `Path` 对象通过 `yield` 返回,作为生成器的值。 16. `if entry.is_dir() and depth > 0:` :如果当前元素是目录,并且深度仍可递归。 17. `yield from walk_to_find_directories(entry.path, depth)` :通过 `yield from` 关键字将递归遍历后生成的生成器添加到当前生成器中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值