fnmatch()函数匹配能力介于简单的字符串方法和强大的正则表达式之间,如果在数据处理操作中只需要简单的通配符就能完成的时候,这通常是一个比较合理的方案。此模块的主要作用是文件名称的匹配,并且匹配的模式使用的Unix shell风格。源码很简单:

  1. """Filename matching with shell patterns.
  2. fnmatch(FILENAME, PATTERN) matches according to the local convention.
  3. fnmatchcase(FILENAME, PATTERN) always takes case in account.
  4. The functions operate by translating the pattern into a regular
  5. expression. They cache the compiled regular expressions for speed.
  6. The function translate(PATTERN) returns a regular expression
  7. corresponding to PATTERN. (It does not compile it.)
  8. """
  9. import os
  10. import posixpath
  11. import re
  12. import functools
  13. __all__ = ["filter", "fnmatch", "fnmatchcase", "translate"]
  14. def fnmatch(name, pat):
  15. """Test whether FILENAME matches PATTERN.
  16. Patterns are Unix shell style:
  17. * matches everything
  18. ? matches any single character
  19. [seq] matches any character in seq
  20. [!seq] matches any char not in seq
  21. An initial period in FILENAME is not special.
  22. Both FILENAME and PATTERN are first case-normalized
  23. if the operating system requires it.
  24. If you don't want this, use fnmatchcase(FILENAME, PATTERN).
  25. """
  26. name = os.path.normcase(name)
  27. pat = os.path.normcase(pat)
  28. return fnmatchcase(name, pat)
  29. @functools.lru_cache(maxsize=256, typed=True)
  30. def _compile_pattern(pat):
  31. if isinstance(pat, bytes):
  32. pat_str = str(pat, 'ISO-8859-1')
  33. res_str = translate(pat_str)
  34. res = bytes(res_str, 'ISO-8859-1')
  35. else:
  36. res = translate(pat)
  37. return re.compile(res).match
  38. def filter(names, pat):
  39. """Return the subset of the list NAMES that match PAT."""
  40. result = []
  41. pat = os.path.normcase(pat)
  42. match = _compile_pattern(pat)
  43. if os.path is posixpath:
  44. # normcase on posix is NOP. Optimize it away from the loop.
  45. for name in names:
  46. if match(name):
  47. result.append(name)
  48. else:
  49. for name in names:
  50. if match(os.path.normcase(name)):
  51. result.append(name)
  52. return result
  53. def fnmatchcase(name, pat):
  54. """Test whether FILENAME matches PATTERN, including case.
  55. This is a version of fnmatch() which doesn't case-normalize
  56. its arguments.
  57. """
  58. match = _compile_pattern(pat)
  59. return match(name) is not None
  60. def translate(pat):
  61. """Translate a shell PATTERN to a regular expression.
  62. There is no way to quote meta-characters.
  63. """
  64. i, n = 0, len(pat)
  65. res = ''
  66. while i < n:
  67. c = pat[i]
  68. i = i+1
  69. if c == '*':
  70. res = res + '.*'
  71. elif c == '?':
  72. res = res + '.'
  73. elif c == '[':
  74. j = i
  75. if j < n and pat[j] == '!':
  76. j = j+1
  77. if j < n and pat[j] == ']':
  78. j = j+1
  79. while j < n and pat[j] != ']':
  80. j = j+1
  81. if j >= n:
  82. res = res + '\\['
  83. else:
  84. stuff = pat[i:j].replace('\\','\\\\')
  85. i = j+1
  86. if stuff[0] == '!':
  87. stuff = '^' + stuff[1:]
  88. elif stuff[0] == '^':
  89. stuff = '\\' + stuff
  90. res = '%s[%s]' % (res, stuff)
  91. else:
  92. res = res + re.escape(c)
  93. return r'(?s:%s)\Z' % res

fnmatch的中的5个函数["filter", "fnmatch", "fnmatchcase", "translate"]

  • filter 返回列表形式的结果
  1. def gen_find(filepat, top):
  2. """
  3. 查找符合Shell正则匹配的目录树下的所有文件名
  4. :param filepat: shell正则
  5. :param top: 目录路径
  6. :return: 文件绝对路径生成器
  7. """
  8. for path, _, filenames in os.walk(top):
  9. for file in fnmatch.filter(filenames, filepat):
  10. yield os.path.join(path, file)
  • fnmatch
  1. 电动叉车
  2. # 列出元组中所有的python文件
  3. pyfiles = [py for py in ('restart.py', 'index.php', 'file.txt') if fnmatch(py, '*.py')]
  4. # 字符串的 startswith() 和 endswith() 方法对于过滤一个目录的内容也是很有用的
  • fnmatchcase 区分大小写的文件匹配
  1. # 这两个函数通常会被忽略的一个特性是在处理非文件名的字符串时候它们也是很有用的。 比如,假设你有一个街道地址的列表数据
  2. address = [
  3. '5412 N CLARK ST',
  4. '1060 W ADDISON ST',
  5. '1039 W GRANVILLE AVE',
  6. '2122 N CLARK ST',
  7. '4802 N BROADWAY',
  8. ]
  9. print([addr for addr in address if fnmatchcase(addr, '* ST')])
  • translate 这个似乎很少有人用到,前面说了fnmatch是Unix shell匹配风格,可以使用translate将其转换为正则表达式,举个栗子
  1. shell_match = 'Celery_?*.py'
  2. print(translate(shell_match))
  3. # 输出结果:(?s:Celery_..*\.py)\Z

Celery_..*\.py就是正则表达式的写法。

Python中fnmatch模块的使用的更多相关文章

  1. Python中optionParser模块的使用方法[转]

    本文以实例形式较为详尽的讲述了Python中optionParser模块的使用方法,对于深入学习Python有很好的借鉴价值.分享给大家供大家参考之用.具体分析如下: 一般来说,Python中有两个内 ...

  2. python中threading模块详解(一)

    python中threading模块详解(一) 来源 http://blog.chinaunix.net/uid-27571599-id-3484048.html threading提供了一个比thr ...

  3. 【转】关于python中re模块split方法的使用

    注:最近在研究文本处理,需要用到正则切割文本,所以收索到了这篇文章,很有用,谢谢原作者. 原址:http://blog.sciencenet.cn/blog-314114-775285.html 关于 ...

  4. Python中的模块介绍和使用

    在Python中有一个概念叫做模块(module),这个和C语言中的头文件以及Java中的包很类似,比如在Python中要调用sqrt函数,必须用import关键字引入math这个模块,下面就来了解一 ...

  5. python中导入模块的本质, 无法导入手写模块的解决办法

    最近身边一些朋友发生在项目当中编写自己模块,导入的时候无法导入的问题. 下面我来分享一下关于python中导入模块的一些基本知识. 1 导入模块时寻找路径 在每一个运行的python程序当中,都维护了 ...

  6. Python中time模块详解

    Python中time模块详解 在平常的代码中,我们常常需要与时间打交道.在Python中,与时间处理有关的模块就包括:time,datetime以及calendar.这篇文章,主要讲解time模块. ...

  7. Python中collections模块

    目录 Python中collections模块 Counter defaultdict OrderedDict namedtuple deque ChainMap Python中collections ...

  8. Python中pathlib模块

    Python中pathlib模块 Path.cwd():返回当前目录的路径 Path.home():返回当前用户的家目录 Path.stat():返回此路径信息 Path.touch():创建文件 P ...

  9. Python 中包/模块的 `import` 操作

    版权声明:博客为作者原创,允许转载,但必须注明原文地址: https://www.cnblogs.com/byronxie/p/10745292.html 用实例来说明 import 的作用吧. 创建 ...

随机推荐

  1. 简单的XSS手动测试

    好吧,我也是初学者,写这个随笔,主要也是为了记录,自学到的点. 简单的案例,见http://www.cnblogs.com/trhimily/p/3898915.html 总结一下主要的点: 1. u ...

  2. head头的设计:rfcn light-head rfcn

    faster缺点:1.不是全卷积,roi出来后是两个fc层,这样会丧失平移变性.   2.每个roi都要单独经过两个fc层,也就是分别进行分类和回归,耗时 也有种说法是roi-pooling后导致平移 ...

  3. Spring事务(三)事务增强器

    摘要: 本文结合<Spring源码深度解析>来分析Spring 5.0.6版本的源代码.若有描述错误之处,欢迎指正. 目录 一.创建事务 1. 获取事务 2. 处理已经存在的事务 3. 准 ...

  4. Uva514

    https://vjudge.net/problem/UVA-514 #include <bits/stdc++.h> using namespace std; ; int target[ ...

  5. RegExp exec有记忆性的问题

    当 RegExpObject 是作为一个变量时时.每次调用完exec()后.它会在 RegExpObject 的 lastIndex 属性指定的字符处开始检索字符串 string.当 exec() 找 ...

  6. SD卡受损,千万不要再格式化了

    1.手机提示SD卡受损; 2.把内卡插入电脑后,提示格式化,点取消.然后查看一下属性; 3.点电脑上的“开始菜单”--“运行”- chkdsk H:/F (H:就是你的SD卡盘符,/F是修复参数); ...

  7. .NET 操作 EventLog(Windows事件日志监控)(转载)

    操作Windows日志:EventLog 如果要在.NET Core控制台项目中使用EventLog(Windows事件日志监控),首先需要下载Nuget包: System.Diagnostics.E ...

  8. 联想ERP项目实施案例分析(10):回到最初再反思IT价值

    联想ERP项目实施案例分析(10):回到最初再反思IT价值 投入上千万(未来每年的维护费也非常高),投入一年实施时间,高级副总裁亲自挂帅,各级业务部门管理者亲自负责.骨干业务人员充当区域IT实施者/推 ...

  9. 关于Android

    1:Handle与多线程 Handle是什么?官方说明:handle是Android给我们提供用来更新UI的一套机制,也是一套消息处理的机制.可以看出handle主要就是两个功能,一个是更新UI,另一 ...

  10. JavaScript总结(四)

    详解BOM(浏览器对象模型(Browser Object Model)) ✍ Window对象方法 方法 描述 alert() 显示带有一段消息和一个确认按钮的警告框 blur() 把键盘焦点从顶层窗 ...