2012年5月14日 星期一

[Python Std Library] File and Directory Access : fnmatch — Unix filename pattern matching


來源自 這裡
Preface :
This module provides support for Unix shell-style wildcards, which are not the same as regular expressions (which are documented in the re module). The special characters used in shell-style wildcards are :


Note that the filename separator ('/' on Unix) is not special to this module. See module glob for pathname expansion (glob uses fnmatch() to match pathname segments). Similarly, filenames starting with a period are not special for this module, and are matched by the * and ? patterns.

Supported APIs :
fnmatch.fnmatch(filename, pattern)
Test whether the filename string matches the pattern string, returning True or False. If the operating system is case-insensitive, then both parameters will be normalized to all lower- or upper-case before the comparison is performed. fnmatchcase() can be used to perform a case-sensitive comparison, regardless of whether that’s standard for the operating system.

This example will print all file names in the current directory with the extension .txt :
  1. import fnmatch  
  2. import os  
  3.   
  4. for file in os.listdir('.'):  
  5.     if fnmatch.fnmatch(file, '*.txt'):  
  6.         print file  

fnmatch.fnmatchcase(filename, pattern)
Test whether filename matches pattern, returning True or False; the comparison is case-sensitive.

fnmatch.filter(names, pattern)
New in version 2.2.
Return the subset of the list of names that match pattern. It is the same as [n for n in names if fnmatch(n, pattern)], but implemented more efficiently.
>>> list = ['a.txt', 'b.doc', 'c.exe', 'd.exe']
>>> fnmatch.filter(list, "*.txt")
['a.txt']
>>> fnmatch.filter(list, "*.exe")
['c.exe', 'd.exe']

fnmatch.translate(pattern)
Return the shell-style pattern converted to a regular expression.

Be aware there is no way to quote meta-characters. Below is usage example :
This message was edited 6 times. Last update was at 11/05/2012 13:18:15

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...