Python 提供多種遍歷目錄的方法,本文對比 os.walk(高階封裝)與 os.scandir(高效底層)的用法、效能差異,並示範如何獲取檔案屬性(大小、建立/修改/存取時間)。
import os
def walk_with_walk(root_dir, output_file):
with open(output_file, 'w', encoding='utf-8') as out:
for dirpath, dirnames, filenames in os.walk(root_dir):
for fname in filenames:
full = os.path.join(dirpath, fname)
out.write(full + '\n')
os.scandir() 回傳 DirEntry 物件,內含檔案屬性,避免額外 stat 系統呼叫:
import os
import time
def format_time(ts):
return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(ts))
def walk_with_scandir(root_dir, output_file):
with open(output_file, 'w', encoding='utf-8') as out:
def scan_dir(path):
with os.scandir(path) as it:
for entry in it:
full = entry.path
stat = entry.stat() # 快速取得屬性
ftype = 'DIR' if entry.is_dir() else 'FILE'
out.write(
f'【{ftype}】路徑:{full} '
f'大小(B):{stat.st_size} '
f'建立:{format_time(stat.st_ctime)} '
f'修改:{format_time(stat.st_mtime)} '
f'存取:{format_time(stat.st_atime)}\n'
)
if entry.is_dir():
scan_dir(full) # 遞迴
scan_dir(root_dir)
| 指標 | os.walk | os.scandir |
|---|---|---|
| API 風格 | 生成器,三元組 (dirpath, dirnames, filenames) | 迭代器,DirEntry 物件 |
| 檔案屬性存取 | 需額外呼叫 os.stat/os.path.getsize | entry.stat() / entry.is_dir() 即時可用 |
| 系統呼叫次數 | 較多 (每檔案至少 1 次 stat) | 極少 (目錄讀取時已取得基本屬性) |
| 適用場景 | 簡單遍歷、相容舊版 Python | 大量檔案、需檔案屬性、高效能需求 |
def collect_files(root):
'''返回所有檔案完整路徑列表 (非遞迴寫法,避免深度過大)'''
files = []
stack = [root]
while stack:
dirpath = stack.pop()
with os.scandir(dirpath) as it:
for entry in it:
if entry.is_dir():
stack.append(entry.path)
else:
files.append(entry.path)
return files
os.walk 寫法最簡潔。os.scandir 效能優勢明顯。os.scandir。