os.walk without digging into directories below

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

提交回复
热议问题