简体   繁体   English

使用 os.walk 排除根目录

[英]Exclude root directories using os.walk

I'm trying to list all the files my laptop but I want to exclude some root directories.我正在尝试列出我的笔记本电脑的所有文件,但我想排除一些根目录。

For example: I have the follwoing files:例如:我有以下文件:

 /Users/teste/demo/file.csv
 /Users/teste/demo3/file.csv
 /Users/project/file.csv

What I want is to exclude all the files from /Users/teste/ .我想要的是从/Users/teste/中排除所有文件。 For that I have this code:为此,我有以下代码:

import os
exclude = ['/Users/teste/',]
for root, dirs, files in os.walk("\\", topdown=False):
    if root not in exclude:
        for name in files:
            print(name)

However, my code is printing the files from directory demo and demo3 because the root include the demo part.但是,我的代码正在打印目录 demo 和 demo3 中的文件,因为根目录包含演示部分。 If I print the root I will get:如果我打印根目录,我将得到:

/Users/teste/demo 
/Users/teste/demo3 
/Users/project/

And I want to include only the /Users/project/file.csv file我只想包含/Users/project/file.csv文件

How can I filter using the parent root?如何使用父根进行过滤?

You can use startswith with tuple (not list)您可以使用带有tuplestartswith (不是列表)

if not root.startswith( ('/Users/teste/', '/other/folder') ):

import os

exclude = ['/Users/teste/',]

exclude = tuple(exclude)

for root, dirs, files in os.walk("\\", topdown=False):
    if not root.startswith(exclude):
        for name in files:
            print(name)

BTW:顺便提一句:

If you want to use function which can't get list or tuple then you can use any() with list comprehension to check all elements on list如果您想使用无法获取列表或元组的 function ,那么您可以使用带有列表理解的any()来检查列表中的所有元素

For example for startswith()例如对于startswith()

if not any(root.startswith(x) for x in exclude):

or for regex (which can be useful to create more complex element in exclude )或用于regex (这对于在exclude中创建更复杂的元素很有用)

if not any(re.findall(x, root) for x in exclude):

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

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