我试图列出我笔记本电脑上的所有文件,但我想排除一些根目录
例如: 我有以下文件:
/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
文件
如何使用父根进行筛选
您可以将
startswith
与tuple
(非列表)一起使用顺便说一句:
若您想使用无法获取列表或元组的函数,那个么可以使用
any()
和列表理解来检查列表中的所有元素例如
startswith()
或者对于
regex
(这对于在exclude
中创建更复杂的元素非常有用)相关问题 更多 >
编程相关推荐