os.walk without hidden folders

后端 未结 3 1814
悲哀的现实
悲哀的现实 2020-11-30 06:17

I need to list all files with the containing directory path inside a folder. I tried to use os.walk, which obviously would be the perfect solution.

Howe

3条回答
  •  一个人的身影
    2020-11-30 07:02

    No, there is no option to os.walk() that'll skip those. You'll need to do so yourself (which is easy enough):

    for root, dirs, files in os.walk(path):
        files = [f for f in files if not f[0] == '.']
        dirs[:] = [d for d in dirs if not d[0] == '.']
        # use files and dirs
    

    Note the dirs[:] = slice assignment; os.walk recursively traverses the subdirectories listed in dirs. By replacing the elements of dirs with those that satisfy a criteria (e.g., directories whose names don't begin with .), os.walk() will not visit directories that fail to meet the criteria.

    This only works if you keep the topdown keyword argument to True, from the documentation of os.walk():

    When topdown is True, the caller can modify the dirnames list in-place (perhaps using del or slice assignment), and walk() will only recurse into the subdirectories whose names remain in dirnames; this can be used to prune the search, impose a specific order of visiting, or even to inform walk() about directories the caller creates or renames before it resumes walk() again.

提交回复
热议问题