[英]Exclude files with fnmatch
I am creating a loop in Python that runs through all files in specific directory using fnmatch.filter()
.我正在 Python 中创建一个循环,该循环使用
fnmatch.filter()
特定目录中的所有文件。 Currently I am going through all .csv files in specific folder as following:目前我正在浏览特定文件夹中的所有 .csv 文件,如下所示:
for file_source in fnmatch.filter(os.listdir(source_dir), "*.csv")
What I would like to do is exclude files with pattern "Test*".我想要做的是排除模式为“Test*”的文件。 Is that somehow possible to do with fnmatch.
这是否可能与 fnmatch. In worst case I would just create another internal if loop, but would prefer a cleaner solution.
在最坏的情况下,我只会创建另一个内部 if 循环,但更喜欢更清洁的解决方案。
You can use a list comprehension to filter the filenames:您可以使用列表理解来过滤文件名:
for file_source in [x for x in fnmatch.filter(os.listdir(source_dir), "*.csv") if 'Test' not in x ] :
pass
I am not familiar with fnmatch but I tried我不熟悉 fnmatch 但我试过了
if fnmatch.fnmatch(file, 'Test*'):
print(file)
And it worked all right.它工作得很好。 You could also use list comprehension as suggested by Chris.
您也可以按照 Chris 的建议使用列表理解。
How about something like this:这样的事情怎么样:
import re
import os
for file in os.listdir('./'):
rex = '^((?!Test).)*\.csv$'
reobj = re.compile(rex)
obj = reobj.match(file)
if obj != None:
print obj.string
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.