fnmatch Module
fnmatch module ใช้สำหรับ Unix shell-style filename pattern matching เหมือนที่เราใช้ใน terminal เช่น *.txt หรือ file?.py โดยไม่ต้องเขียน regex ที่ซับซ้อน ทำให้โค้ดอ่านง่ายและดูแลรักษาง่ายขึ้น
ทำไมต้องใช้ fnmatch
Section titled “ทำไมต้องใช้ fnmatch”การใช้ fnmatch มีข้อดีหลายประการ:
- Syntax ง่าย - ใช้ pattern เหมือน shell command ที่คุ้นเคย
- อ่านง่าย -
*.txtเข้าใจง่ายกว่าr'.*\.txt$' - เร็ว - ทำงานกับ string โดยไม่ต้องเข้าถึง filesystem
- Portable - ทำงานได้ทุก OS โดยใช้
fnmatchcase()
import fnmatchimport re
# เปรียบเทียบ: regex vs fnmatch
files = ['report.txt', 'data.csv', 'image.png', 'log.txt', 'backup.txt.bak']
# วิธีที่ 1: ใช้ regex - ซับซ้อนและ error-pronepattern = re.compile(r'.*\.txt$') # ต้องระวัง escape characterregex_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 เพื่อปลดล็อกบทความทั้งหมด
Login with Google