python os.walk 指定遍历深度_os.walk 如何设置遍历层级?

本文介绍了如何通过自定义的 lwalk 函数实现类似 os.walk 的功能,但增加了指定遍历深度的选项。lwalk 函数接受 max_level 参数以限制遍历的最大深度,并提供了 topdown 和 followlinks 参数。代码示例展示了如何使用 lwalk 进行深度限制的目录遍历,提高系统效率。
Python3.10

Python3.10

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

仿照 os.walk 寫了一個 generator lwalk, 他的行為如同 os.walk 但是多了一個 max_level 可以控制最大的遍歷深度, 為了與 os.walk 盡量吻合, 我也實作了 topdown 和 followlinks 這兩個 arguments, 但為了不使 code 太過複雜, 我省略了 onerror 參數的實作以及若干 error handling。

代碼如下:

import os

def lwalk(top, topdown=True, followlinks=False, max_level=None):

if max_level is None:

new_max_level = None

else:

if max_level==0:

return

else:

new_max_level = max_level-1

top = os.fspath(top)

dirs, nondirs, walk_dirs = [], [], []

with os.scandir(top) as it:

for entry in it:

if entry.is_dir():

dirs.append(entry.name)

else:

nondirs.append(entry.name)

if not topdown and entry.is_dir():

if followlinks or not entry.is_symlink():

walk_dirs.append(entry.path)

if topdown:

yield top, dirs, nondirs

for dirname in dirs:

new_path = os.path.join(top, dirname)

if followlinks or not os.path.islink(new_path):

yield from lwalk(new_path, topdown, followlinks, new_max_level)

else:

for new_path in walk_dirs:

yield from lwalk(new_path, topdown, followlinks, new_max_level)

yield top, dirs, nondirs

簡單的範例如下:

for root, dirs, files in lwalk('YOUR_TOP_PATH', max_level=4):

print(root, dirs, files)

一些說明:

核心在於使用 os.scandir 來保證系統遍歷的效率

使用 max_level 來控制最大遍歷深度, 在 recursively 進入下一層的時候, 將最大深度減 1

要實作 buttom up, 則需先 recursively 進入下一層再 yield 目錄與文件

這邊有一個省略掉 topdown, followlink 和若干處理的簡單版本, 可以幫助你觀察一下核心的實作手段:

import os

def lwalk(top, max_level=10000):

if max_level==0:

return

dirs, nondirs = [], []

with os.scandir(top) as it:

for entry in it:

if entry.is_dir():

dirs.append(entry.name)

else:

nondirs.append(entry.name)

yield top, dirs, nondirs

for dirname in dirs:

new_path = os.path.join(top, dirname)

yield from lwalk(new_path, max_level-1)

for root, dirs, files in lwalk('a', max_level=4):

print(root, dirs, files)

您可能感兴趣的与本文相关的镜像

Python3.10

Python3.10

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值