使用os.walk排除根目录

佩德罗·阿尔维斯(Pedro Alves)

我正在尝试列出笔记本电脑中的所有文件,但我想排除一些根目录。

例如:我有以下文件:

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

我要从中排除所有文件/Users/teste/为此,我有以下代码:

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)

但是,我的代码正在打印目录demo和demo3中的文件,因为根目录包含了demo部分。如果我打印根,我将得到:

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

我只想包含/Users/project/file.csv文件

如何使用父根进行过滤?

简单

可以startswithtuple(不列出)一起使用

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)

顺便说一句:

如果要使用无法获取列表或元组的函数,则可以any()与列表理解一起使用以检查列表中的所有元素

例如 startswith()

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

regex(对于在中创建更复杂的元素可能很有用exclude

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章