在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Python/ os.walk 如何設(shè)置遍歷層級(jí)?

os.walk 如何設(shè)置遍歷層級(jí)?

linux 下有find -maxdepth 4設(shè)置層級(jí),但是windows下沒有該命令,但是程序又需要在windows下運(yùn)行

所以想問下python是否有辦法可以實(shí)現(xiàn)指定最大遍歷層級(jí),節(jié)省時(shí)間,提高效率?

回答
編輯回答
熊出沒

仿照 os.walk 寫了一個(gè) generator lwalk, 他的行為如同 os.walk 但是多了一個(gè) max_level 可以控制最大的遍歷深度, 為了與 os.walk 盡量吻合, 我也實(shí)作了 topdownfollowlinks 這兩個(gè) arguments, 但為了不使 code 太過複雜, 我省略了 onerror 參數(shù)的實(shí)作以及若干 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

簡(jiǎn)單的範(fàn)例如下:

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

一些說明:

  1. 核心在於使用 os.scandir 來保證系統(tǒng)遍歷的效率

  2. 使用 max_level 來控制最大遍歷深度, 在 recursively 進(jìn)入下一層的時(shí)候, 將最大深度減 1

  3. 要實(shí)作 buttom up, 則需先 recursively 進(jìn)入下一層再 yield 目錄與文件

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

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)

我回答過的問題: Python-QA

2018年5月31日 06:09
編輯回答
何蘇葉

改用listdir手動(dòng)造輪子吧,搜一下有好多現(xiàn)成的_(:з」∠)_
比如:http://blog.csdn.net/yu12377/...

2017年6月4日 17:32