简体   繁体   English

使用 fnmatch 排除文件

[英]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.

相关问题 fnmatch.fnmatch 使用模式排除子目录 - fnmatch.fnmatch use a pattern to exclude sub directories Python-为什么fnmatch匹配子目录中的文件? - Python - Why does fnmatch match files in subdirs? 使用oswalk + fnmatch输出*准确的Python 2文件的绝对路径 - Print out *accurate* absolute path to files in Python 2 with oswalk + fnmatch Python-列出目录中文件的fnmatch函数保留先前的内容 - Python - fnmatch function that lists files in a directory keeps previous contents 在 a) 目录中的所有文件和 b) 不使用 fnmatch 的文件的 txt 列表之间查找匹配项 - python - finding matches between a) all the files in a directory and b) a txt list of files not working with fnmatch - python Python 中是否有一种方法可以在不使用 os.walk、glob 或 fnmatch 的情况下递归搜索目录、子目录和文件? - Is there a way in Python to search directories, subdirectories and files recursively without using os.walk, glob, or fnmatch? 使用 fnmatch.filter 通过多个可能的文件扩展名过滤文件 - Use fnmatch.filter to filter files by more than one possible file extension python fnmatch.fnmatch("[seq]") 转义不起作用 - python fnmatch.fnmatch("[seq]") escape not working 排除字典中的文件 - Exclude files in a dictionary 带括号和逗号的 Python fnmatch - Python fnmatch with parentheses and commas
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM