使用 fnmatch 排除文件

Exclude files with fnmatch

我正在 Python 中创建一个循环,它使用 fnmatch.filter() 遍历特定目录中的所有文件。目前我正在浏览特定文件夹中的所有 .csv 文件,如下所示:

for file_source in fnmatch.filter(os.listdir(source_dir), "*.csv")

我想做的是排除模式为 "Test*" 的文件。这在某种程度上可能与 fnmatch 相关吗?在最坏的情况下,我只会创建另一个内部 if 循环,但更喜欢更简洁的解决方案。

您可以使用列表理解来过滤文件名:

for file_source in [x for x in fnmatch.filter(os.listdir(source_dir), "*.csv") if 'Test' not in x ] :
     pass

我不熟悉 fnmatch 但我试过了

   if fnmatch.fnmatch(file, 'Test*'):
       print(file)

而且一切正常。您也可以按照克里斯的建议使用列表理解。

这样的事情怎么样:

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