โมดูล fnmatch ใช้จับคู่ชื่อไฟล์แบบ Unix Shell Wildcard คืนค่า True/False อยู่ใน Standard Library
import fnmatch
Wildcard Patterns
| Pattern | ความหมาย |
|---|---|
* | จับคู่อะไรก็ได้ (0 ตัวขึ้นไป) |
? | จับคู่ตัวอักษรเดี่ยว 1 ตัว |
[seq] | จับคู่ตัวอักษรในชุด seq (เช่น [abc]) |
[!seq] | จับคู่ตัวอักษรที่ ไม่อยู่ ใน seq |
ถ้าต้องการจับคู่ * หรือ ? ตรงตัว ให้ใช้ [*] หรือ [?]
1. fnmatch.fnmatch(filename, pattern)
ตรวจสอบไฟล์เดี่ยวตรงกับ Pattern หรือไม่
import fnmatch
import os
pattern = 'test_f*'
files = os.listdir('./unix_files')
for f in files:
print(f'File: {f}\t: {fnmatch.fnmatch(f, pattern)}')
ผลลัพธ์
File: test_file5.txt : True File: test_file2.png : True File: test_file1.txt : True File: another_file.txt : False File: TEST_FILE4.txt : False (Case-sensitive) File: abc.txt : False File: test_file3.txt : True
2. fnmatch.filter(names, pattern)
คืน List ของไฟล์ที่ Match ทั้งหมด
matched = fnmatch.filter(files, pattern)
print('All files:', files)
print('Matched files:', matched)
ผลลัพธ์
Matched files: ['test_file5.txt', 'test_file2.png', 'test_file1.txt', 'test_file3.txt']
3. fnmatch.translate(pattern)
แปลง Shell Pattern -> Regular Expression
import fnmatch, re
pattern = 'test_f*.txt'
regex = fnmatch.translate(pattern)
# (?s:test_f.*\.txt)\Z
regex_obj = re.compile(regex)
print(regex_obj.match('test_file_abcd123.txt'))
#
Case Sensitivity
- Unix: Case-sensitive โดยค่าเริ่มต้น
- Windows: Case-insensitive
- ใช้
fnmatch.fnmatchcase()บังคับ Case-sensitive
กรณีใช้งานจริง
- ค้นหาไฟล์ Log:
app-*.log - Filter นามสกุล:
*.py,*.{jpg,png} - Batch Processing: ประมวลผลเฉพาะไฟล์ที่ Match Pattern