技術部落格:
儘管glob
api 不多,但該模組具有很強的功能。當程式需要通過名稱與模式匹配的方式查詢檔案列表時,它很有用。要建立乙個檔案列表,這些檔名具有特定的副檔名,字首或中間的任何公共字串,這個時候,使用glob
而不是編寫自定義**來掃瞄目錄內容。
glob
模式規則與re
模組使用的正規表示式不同。相反,它們遵循標準的 unix 路徑擴充套件規則,只有少數特殊字元用於實現兩個不同的萬用字元和字元範圍。模式規則應用於檔名段(在路徑分隔符處停止/
),模式中的路徑可以是相對的或絕對的,shell 變數名和波浪號(~
)不會展開。
本節中的示例假定當前工作目錄中存在以下測試檔案。
星號(dir
dir/
file
.txt
dir/file1.txt
dir/file2.txt
dir/filea.txt
dir/fileb.txt
dir/
file?.txt
dir/
file
*.txt
dir/
file
[.txt
dir/subdir
dir/subdir/subfile.txt
*
)匹配名稱段中的零個或多個字元。例如,dir/*
。
該模式匹配目錄 dir 中的每個路徑名(檔案或目錄),而不會進一步遞迴到子目錄中。返回的資料未排序,因此這裡的示例對其進行排序以便更直觀地展示結果。import glob
for name in
sorted
(glob.glob(
'dir/*'))
(name)
# output
# dir/file *.txt
# dir/file.txt
# dir/file1.txt
# dir/file2.txt
# dir/file?.txt
# dir/file[.txt
# dir/filea.txt
# dir/fileb.txt
# dir/subdir
要列出子目錄中的檔案,子目錄必須包含在模式中。
前面顯示的第一種情況明確列出了子目錄名稱,而第二種情況依賴於萬用字元來查詢目錄。import glob
('named explicitly:'
)for name in
sorted
(glob.glob(
'dir/subdir/*'))
(' {}'
.format
(name)
('named with wildcard:'
)for name in
sorted
(glob.glob(
'dir/*/*'))
(' {}'
.format
(name)
)# output
# named explicitly:
# dir/subdir/subfile.txt
# named with wildcard:
# dir/subdir/subfile.txt
在這種情況下,結果是相同的。如果有另乙個子目錄,則萬用字元將匹配兩個子目錄幷包含兩者的檔名。
問號(?
)是另乙個萬用字元。它匹配名稱中該位置的任何單個字元。
示例匹配所有以import glob
for name in
sorted
(glob.glob(
'dir/file?.txt'))
(name)
# output
# dir/file*.txt
# dir/file1.txt
# dir/file2.txt
# dir/file?.txt
# dir/file[.txt
# dir/filea.txt
# dir/fileb.txt
file
開頭的檔名,具有任何型別的單個字元,然後以.txt
結束。
使用字元範圍([a-z]
)而不是問號來匹配多個字元之一。此示例在副檔名之前查詢名稱中帶有數字的所有檔案。
字元範圍import glob
for name in
sorted
(glob.glob(
'dir/*[0-9].*'))
(name)
# output
# dir/file1.txt
# dir/file2.txt
[0-9]
匹配任何單個數字。範圍根據每個字母/數字的字元**排序,短劃線表示連續字元的連續範圍。可以寫入相同的範圍值[0123456789]
。
有時需要搜尋名稱中包含特殊元字元(glob
用於模式匹配)的檔案。escape()
函式使用特殊字元「轉義」構建合適的模式,因此它們不會被擴充套件或解釋為特殊字元。
通過構建包含單個條目的字元範圍來轉義每個特殊字元。import glob
specials =
'?*['
for char in specials:
pattern =
'dir/*'
+ glob.escape(char)
+'.txt'
('searching for: '
.format
(pattern)
)for name in
sorted
(glob.glob(pattern)):
(name)
print()
# output
# searching for: 'dir/*[?].txt'
# dir/file?.txt
# # searching for: 'dir/*[*].txt'
# dir/file*.txt
# # searching for: 'dir/*[.txt'
# dir/file[.txt
每週乙個 Python 標準庫 struct
技術部落格 structs 支援將資料打包成字串,並使用格式說明符從字串中解壓縮資料,格式說明符由表示資料型別的字元 可選計數和位元組順序指示符組成。有關支援的格式說明符的完整列表,請參閱標準庫文件。在此示例中,說明符呼叫整數或長整數值,雙位元組字串和浮點數。格式說明符中的空格用作分隔型別指示符,並...
每週乙個 Python 模組 string
每週乙個 python 模組 目的 包含用於處理文字的常量和類。string 模組可以追溯到最早的 python 版本。先前在此模組中實現的許多功能已移至 str 物件方法。string 模組保留了幾個有用的常量和類來處理 str 物件。直接看下面的事例 import string s the qu...
每週乙個 Python 模組 fnmatch
每週乙個 python 模組 fnmatch 模組主要用於檔名的比較,使用 unix shell 使用的 glob 樣式模式。fnmatch 將單個檔名與模式進行比較並返回布林值,來看它們是否匹配。當作業系統使用區分大小寫的檔案系統時,比較區分大小寫。import fnmatch import os...