Non-recursive os.walk()

2020-02-03 09:28发布

I'm looking for a way to do a non-recursive os.walk() walk, just like os.listdir() works. But I need to return in the same way the os.walk() returns. Any idea?

Thank you in advance.

4条回答
何必那么认真
2楼-- · 2020-02-03 09:50
next(os.walk(...))
查看更多
3楼-- · 2020-02-03 09:52

Add a break after the filenames for loop:

for root, dirs, filenames in os.walk(workdir):
    for fileName in filenames:
        print (fileName)
    break   #prevent descending into subfolders

This works because (by default) os.walk first lists the files in the requested folder and then goes into subfolders.

查看更多
老娘就宠你
4楼-- · 2020-02-03 09:58

My a bit more parametrised solution would be this:

for root, dirs, files in os.walk(path):  
    if not recursive:  
        while len(dirs) > 0:  
            dirs.pop()  

    //some fency code here using generated list

Edit: fixes, if/while issue. Thanks, @Dirk van Oosterbosch :}

查看更多
啃猪蹄的小仙女
5楼-- · 2020-02-03 10:03

Well what Kamiccolo meant was more in line with this:

for str_dirname, lst_subdirs, lst_files in os.walk(str_path):
    if not bol_recursive:
          while len(lst_subdirs) > 0:
              lst_subdirs.pop()
查看更多
登录 后发表回答