在檔案處理任務中,獲取目錄下符合特定條件的檔案清單是基礎操作。Python 標準庫 os 與 glob 提供了多種靈活的方式,本文整理出最常用、最 Pythonic 的幾種寫法,並對比其優缺點。
os.listdir + 字串判斷(基礎版)import os
def get_file_list_basic(path, extensions=None):
"""取得檔案清單,可選擇性依副檔名過濾"""
files = []
for fname in os.listdir(path):
full = os.path.join(path, fname)
if os.path.isfile(full):
if extensions is None or any(fname.lower().endswith(ext) for ext in extensions):
files.append(full)
return sorted(files)
# 使用範例
txt_files = get_file_list_basic('.', ['.txt', '.log'])
print(txt_files)
glob.glob(模式比對,語意清晰)import glob
# 遞迴搜尋所有 .py 檔案
py_files = glob.glob('**/*.py', recursive=True)
# 非遞迴,僅當前目錄
csv_files = glob.glob('*.csv')
優點:支援萬用字元、遞迴搜尋、程式碼簡潔。
缺點:大量檔案時記憶體佔用較高(一次回傳列表)。
os.scandir(Python 3.5+,高效能)import os
def get_file_list_fast(path, ext_filter=None):
"""使用 DirEntry 物件,避免重複 stat 系統呼叫"""
with os.scandir(path) as it:
for entry in it:
if entry.is_file():
if ext_filter is None or entry.name.lower().endswith(ext_filter):
yield entry.path
# 使用生成器逐一處理,記憶體友善
for fpath in get_file_list_fast('.', '.json'):
print(fpath)
os.scandir 回傳 os.DirEntry 物件,已快取 is_file()、stat() 等資訊,效能優於 listdir + os.path.join + os.path.isfile 的組合。
pathlib(物件導向,現代 Python 風格)from pathlib import Path
root = Path('.')
# 遞迴取得所有 .md 檔案
md_files = list(root.rglob('*.md'))
# 僅當前目錄
log_files = list(root.glob('*.log'))
# 進階過濾:檔案大小 > 1MB 且修改時間在 7 天內
import time
recent_large = [
f for f in root.rglob('*')
if f.is_file() and f.stat().st_size > 1_000_000 and (time.time() - f.stat().st_mtime) < 7*86400
]
pathlib.Path 提供豐富的屬性與方法(.suffix, .stem, .parent 等),程式碼可讀性極高,是 Python 3.4+ 專案的首選。
| 場景 | 推薦方法 | 理由 |
|---|---|---|
| 簡單腳本、檔案數 < 1萬 | glob.glob 或 pathlib | 寫法簡潔,維護容易 |
| 大量檔案(十萬以上)、需高效能 | os.scandir 生成器 | 低記憶體、少系統呼叫 |
| 需複雜過濾條件(大小、時間、權限) | pathlib + 列表推導 | 物件屬性豐富,邏輯直觀 |
| 相容 Python 2.7 老專案 | os.listdir + 手動過濾 | 無第三方依賴,相容性最好 |
def filter_files(paths, predicates):
"""通用過濾器:paths 為可迭代物件,predicates 為可呼叫物件列表"""
for p in paths:
if all(pred(p) for pred in predicates):
yield p
# 定義條件
is_py = lambda p: p.endswith('.py')
not_test = lambda p: 'test' not in p
large = lambda p: os.path.getsize(p) > 1024
# 組合使用
for f in filter_files(glob.glob('**/*.py', recursive=True), [is_py, not_test, large]):
print(f)
Python 提供了多層次的檔案系統 API,從底層的 os.scandir 到高階的 pathlib。根據專案規模、Python 版本與可讀性需求選擇適當工具,能讓檔案搜尋邏輯既高效又易維護。