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

標籤

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

沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!