os.walk without digging into directories below

前端 未结 20 1201
庸人自扰
庸人自扰 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 06:54

    You can use this snippet

    for root, dirs, files in os.walk(directory):
        if level > 0:
            # do some stuff
        else:
            break
        level-=1
    
    0 讨论(0)
  • 2020-12-04 06:55

    create a list of excludes, use fnmatch to skip the directory structure and do the process

    excludes= ['a\*\b', 'c\d\e']
    for root, directories, files in os.walk('Start_Folder'):
        if not any(fnmatch.fnmatch(nf_root, pattern) for pattern in excludes):
            for root, directories, files in os.walk(nf_root):
                ....
                do the process
                ....
    

    same as for 'includes':

    if **any**(fnmatch.fnmatch(nf_root, pattern) for pattern in **includes**):
    
    0 讨论(0)
  • 2020-12-04 06:59

    A slight change to Alex's answer, but using __next__():

    print(next(os.walk('d:/'))[2]) or print(os.walk('d:/').__next__()[2])

    with the [2] being the file in root, dirs, file mentioned in other answers

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

    Don't use os.walk.

    Example:

    import os
    
    root = "C:\\"
    for item in os.listdir(root):
        if os.path.isfile(os.path.join(root, item)):
            print item
    
    0 讨论(0)
  • 2020-12-04 07:02
    for path, dirs, files in os.walk('.'):
        print path, dirs, files
        del dirs[:] # go only one level deep
    
    0 讨论(0)
  • 2020-12-04 07:03

    I think the solution is actually very simple.

    use

    break
    

    to only do first iteration of the for loop, there must be a more elegant way.

    for root, dirs, files in os.walk(dir_name):
        for f in files:
            ...
            ...
        break
    ...
    

    The first time you call os.walk, it returns tulips for the current directory, then on next loop the contents of the next directory.

    Take original script and just add a break.

    def _dir_list(self, dir_name, whitelist):
        outputList = []
        for root, dirs, files in os.walk(dir_name):
            for f in files:
                if os.path.splitext(f)[1] in whitelist:
                    outputList.append(os.path.join(root, f))
                else:
                    self._email_to_("ignore")
            break
        return outputList
    
    0 讨论(0)
提交回复
热议问题