os.walk没有隐藏的文件夹 [英] os.walk without hidden folders

查看:289
本文介绍了os.walk没有隐藏的文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要列出文件夹中包含目录路径的所有文件.我尝试使用os.walk,这显然是完美的解决方案.

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.

但是,它还会列出隐藏的文件夹和文件.我希望我的应用程序不列出任何隐藏的文件夹或文件.有没有可以用来使其不产生任何隐藏文件的标志?

However, it also lists hidden folders and files. I'd like my application not to list any hidden folders or files. Is there any flag you can use to make it not yield any hidden files?

跨平台对我来说并不重要,如果它仅适用于linux(.*模式)

Cross-platform is not really important to me, it's ok if it only works for linux (.* pattern)

推荐答案

不,os.walk()没有选项可以跳过这些内容.您需要自己这样做(这很容易):

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

请注意dirs[:] =切片分配; os.walk递归遍历dirs中列出的子目录.通过将dirs elements 替换为满足条件的元素(例如,名称不以.开头的目录),os.walk()将不会访问不符合条件的目录.

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.

仅当从topdown关键字参数保持为True时,此方法才有效="noreferrer"> os.walk() 的文档:

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

topdownTrue时,调用者可以就地修改目录名称列表(也许使用del或切片分配),并且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.

这篇关于os.walk没有隐藏的文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆