简体   繁体   English

Python os.walk跳过具有特定名称而不是路径的目录

[英]Python os.walk skip directories with specific name instead of path

So I have a file system that I want to be able to check and update using python. 因此,我有一个文件系统,希望能够使用python检查和更新。 my solution was os.walk but it becomes problematic with my needs and my file system. 我的解决方案是os.walk,但是它对我的需求和文件系统造成了问题。 This is how the directories are laid out: 这是目录的布局方式:

Root
dir1
    subdir
        1
        2
        3...
    file1
    file2
dir2
    subdir
        1
        2
        3...
    file1
    file2
...

The main directories have different names hence "dir1" and "dir2" but the directories inside those have the same name as each other and contain a lot of different files and directories. 主目录具有不同的名称,因此为“ dir1”和“ dir2”,但是其中的目录彼此具有相同的名称,并且包含许多不同的文件和目录。 The sub directories are the ones I want to exclude from os.walk as they add unnecessary computing. 子目录是我想从os.walk中排除的目录,因为它们添加了不必要的计算。

Is there a way to exclude directories from os.walk based on the directory's name instead of path or will I need to do something else? 有没有一种方法可以根据目录名而不是路径从os.walk中排除目录,否则我需要做其他事情吗?

os.walk allows you to modify the list of directories it gives you. os.walk允许您修改它给您的目录列表。 If you take some out, it won't descend into those directories. 如果将其取出,它将不会进入这些目录。

for dirpath, dirnames, filenames in os.walk("/root/path"):
    if "subdir" in dirnames:
        dirnames.remove("subdir")
    # process the files here

(Note that this doesn't work if you use the bottom-up style of scanning. The top-down style is the default.) (请注意,如果您使用自下而上的扫描方式,则此方法无效。自上而下的扫描方式是默认方式。)

See the documentation 请参阅说明文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM