每週乙個 Python 模組 fnmatch

2021-09-11 15:04:02 字數 2807 閱讀 7752

每週乙個 python 模組

fnmatch 模組主要用於檔名的比較,使用 unix shell 使用的 glob 樣式模式。

fnmatch()將單個檔名與模式進行比較並返回布林值,來看它們是否匹配。當作業系統使用區分大小寫的檔案系統時,比較區分大小寫。

import fnmatch

import os

pattern = 'fnmatch_*.py'

print('pattern :', pattern)

print()

files = os.listdir('.')

for name in sorted(files):

print('filename: {}'.format(name, fnmatch.fnmatch(name, pattern)))

# output

# pattern : fnmatch_*.py

# # filename: fnmatch_filter.py true

# filename: fnmatch_fnmatch.py true

# filename: fnmatch_fnmatchcase.py true

# filename: fnmatch_translate.py true

# filename: index.rst false

複製**

在此示例中,模式匹配所有以'fnmatch_'開頭和以'.py'結尾的檔案。

要強制進行區分大小寫的比較,無**件系統和作業系統設定如何,請使用fnmatchcase()

import fnmatch

import os

pattern = 'fnmatch_*.py'

print('pattern :', pattern)

print()

files = os.listdir('.')

for name in sorted(files):

print('filename: {}'.format(name, fnmatch.fnmatchcase(name, pattern)))

# output

# pattern : fnmatch_*.py

# # filename: fnmatch_filter.py false

# filename: fnmatch_fnmatch.py false

# filename: fnmatch_fnmatchcase.py false

# filename: fnmatch_translate.py false

# filename: index.rst false

複製**

由於用於測試此程式的 os x 系統使用區分大小寫的檔案系統,因此沒有檔案與修改後的模式匹配。

要測試檔名序列,使用filter(),它返回與pattern引數匹配的名稱列表。

import fnmatch

import os

import pprint

pattern = 'fnmatch_*.py'

print('pattern :', pattern)

files = list(sorted(os.listdir('.')))

print('\nfiles :')

pprint.pprint(files)

print('\nmatches :')

pprint.pprint(fnmatch.filter(files, pattern))

# output

# pattern : fnmatch_*.py

# # files :

# ['fnmatch_filter.py',

# 'fnmatch_fnmatch.py',

# 'fnmatch_fnmatchcase.py',

# 'fnmatch_translate.py',

# 'index.rst']

# # matches :

# ['fnmatch_filter.py',

# 'fnmatch_fnmatch.py',

# 'fnmatch_fnmatchcase.py',

# 'fnmatch_translate.py']

複製**

在此示例中,filter()返回與此部分關聯的示例原始檔的名稱列表。

在內部,fnmatchglob模式轉換為正規表示式,並使用re模組比較名稱和模式。translate()函式是將glob模式轉換為正規表示式的公共 api。

import fnmatch

pattern = 'fnmatch_*.py'

print('pattern :', pattern) # pattern : fnmatch_*.py

print('regex :', fnmatch.translate(pattern)) # regex : (?s:fnmatch_.*\.py)\z

複製**

pymotw.com/3/fnmatch/i…

每週乙個 Python 模組 string

每週乙個 python 模組 目的 包含用於處理文字的常量和類。string 模組可以追溯到最早的 python 版本。先前在此模組中實現的許多功能已移至 str 物件方法。string 模組保留了幾個有用的常量和類來處理 str 物件。直接看下面的事例 import string s the qu...

每週乙個 Python 標準庫 struct

技術部落格 structs 支援將資料打包成字串,並使用格式說明符從字串中解壓縮資料,格式說明符由表示資料型別的字元 可選計數和位元組順序指示符組成。有關支援的格式說明符的完整列表,請參閱標準庫文件。在此示例中,說明符呼叫整數或長整數值,雙位元組字串和浮點數。格式說明符中的空格用作分隔型別指示符,並...

每週乙個 Python 標準庫 glob

技術部落格 儘管globapi 不多,但該模組具有很強的功能。當程式需要通過名稱與模式匹配的方式查詢檔案列表時,它很有用。要建立乙個檔案列表,這些檔名具有特定的副檔名,字首或中間的任何公共字串,這個時候,使用glob而不是編寫自定義 來掃瞄目錄內容。glob模式規則與re模組使用的正規表示式不同。相...