python - os.walk 没有隐藏文件夹

标签 python linux os.walk

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

但是,它也列出了隐藏的文件夹和文件。我希望我的应用程序不列出任何隐藏的文件夹或文件。有没有什么标志可以用来让它不产生任何隐藏文件?

跨平台对我来说并不是很重要,如果它只适用于linux(.*模式)就可以了

最佳答案

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

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元素 替换为满足条件的元素(例如,名称不以 . 开头的目录), os.walk() 不会访问不符合条件的目录。

这仅在您将 topdown 关键字参数保留为 True 时才有效,来自 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.

关于python - os.walk 没有隐藏文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13454164/

相关文章:

python - Python asyncio 是否使用线程池?

python - 查看以前的时间序列

python - 如何在 Windows 上使用 Python 和 Pygame 的网络摄像头? vidcap.错误: Cannot set capture resolution

linux - cd 到第一个 'find' 结果(即使路径包含空格)

python - 如何通过python代码执行awk命令

python - 按顺序对要上传的文件列表进行排序

python - 使用 os.walk 在 python 中仅列出所有带有 png 的子目录

python - Tweepy 引用状态 "Status has no attribute quoted_status"

linux - 在 Rhel 6 上安装 Oracle 11g 64 位

python - 如何使用 os.walk 根据修改日期过滤文件夹?