Skip to content
เข้าสู่ระบบ

fnmatch Module

fnmatch module ใช้สำหรับ Unix shell-style filename pattern matching เหมือนที่เราใช้ใน terminal เช่น *.txt หรือ file?.py โดยไม่ต้องเขียน regex ที่ซับซ้อน ทำให้โค้ดอ่านง่ายและดูแลรักษาง่ายขึ้น

การใช้ fnmatch มีข้อดีหลายประการ:

  1. Syntax ง่าย - ใช้ pattern เหมือน shell command ที่คุ้นเคย
  2. อ่านง่าย - *.txt เข้าใจง่ายกว่า r'.*\.txt$'
  3. เร็ว - ทำงานกับ string โดยไม่ต้องเข้าถึง filesystem
  4. Portable - ทำงานได้ทุก OS โดยใช้ fnmatchcase()
import fnmatch
import re
# เปรียบเทียบ: regex vs fnmatch
files = ['report.txt', 'data.csv', 'image.png', 'log.txt', 'backup.txt.bak']
# วิธีที่ 1: ใช้ regex - ซับซ้อนและ error-prone
pattern = re.compile(r'.*\.txt$') # ต้องระวัง escape character
regex_matches = [f for f in files if pattern.match(f)]
print(f"regex result: {regex_matches}")
# วิธีที่ 2: ใช้ fnmatch - ง่ายและอ่านง่าย
fnmatch_matches = fnmatch.filter(files, '*.txt')
print(f"fnmatch result: {fnmatch_matches}")
# ผลลัพธ์เหมือนกัน แต่ fnmatch อ่านง่ายกว่ามาก
print(f"\nผลลัพธ์เท่ากัน: {regex_matches == fnmatch_matches}")

เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม

ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด