使用os.walk排除根目录

2024-05-21 00:05:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图列出我笔记本电脑上的所有文件,但我想排除一些根目录

例如: 我有以下文件:

 /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文件

如何使用父根进行筛选


Tags: 文件csv代码inprojectforosdemo
1条回答
网友
1楼 · 发布于 2024-05-21 00:05:28

您可以将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):

相关问题 更多 >