os.walk without digging into directories below

前端 未结 20 1204
庸人自扰
庸人自扰 2020-12-04 06:21

How do I limit os.walk to only return files in the directory I provide it?

def _dir_list(self, dir_name, whitelist):
    outputList = []
    for         


        
相关标签:
20条回答
  • 2020-12-04 07:11

    This is how I solved it

    if recursive:
        items = os.walk(target_directory)
    else:
        items = [next(os.walk(target_directory))]
    
    ...
    
    0 讨论(0)
  • 2020-12-04 07:12

    If you have more complex requirements than just the top directory (eg ignore VCS dirs etc), you can also modify the list of directories to prevent os.walk recursing through them.

    ie:

    def _dir_list(self, dir_name, whitelist):
        outputList = []
        for root, dirs, files in os.walk(dir_name):
            dirs[:] = [d for d in dirs if is_good(d)]
            for f in files:
                do_stuff()
    

    Note - be careful to mutate the list, rather than just rebind it. Obviously os.walk doesn't know about the external rebinding.

    0 讨论(0)
  • 2020-12-04 07:13

    Felt like throwing my 2 pence in.

    baselevel = len(rootdir.split("\\"))
    for subdirs, dirs, files in os.walk(rootdir):
        curlevel = len(subdirs.split("\\"))
        if curlevel <= baselevel + 1:
            [do stuff]
    
    0 讨论(0)
  • 2020-12-04 07:13

    Why not simply use a range and os.walk combined with the zip? Is not the best solution, but would work too.

    For example like this:

    # your part before
    for count, (root, dirs, files) in zip(range(0, 1), os.walk(dir_name)):
        # logic stuff
    # your later part
    

    Works for me on python 3.

    Also: A break is simpler too btw. (Look at the answer from @Pieter)

    0 讨论(0)
  • 2020-12-04 07:15

    In Python 3, I was able to do this:

    import os
    dir = "/path/to/files/"
    
    #List all files immediately under this folder:
    print ( next( os.walk(dir) )[2] )
    
    #List all folders immediately under this folder:
    print ( next( os.walk(dir) )[1] )
    
    0 讨论(0)
  • 2020-12-04 07:18

    The suggestion to use listdir is a good one. The direct answer to your question in Python 2 is root, dirs, files = os.walk(dir_name).next().

    The equivalent Python 3 syntax is root, dirs, files = next(os.walk(dir_name))

    0 讨论(0)
提交回复
热议问题