萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 遍歷目錄樹:os.walk 與 os.scandir 實戰比較

Python 提供多種遍歷目錄的方法,本文對比 os.walk(高階封裝)與 os.scandir(高效底層)的用法、效能差異,並示範如何獲取檔案屬性(大小、建立/修改/存取時間)。

方法一:os.walk (傳統、簡便)

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 (Python 3.5+,高效能)

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.walkos.scandir
API 風格生成器,三元組 (dirpath, dirnames, filenames)迭代器,DirEntry 物件
檔案屬性存取需額外呼叫 os.stat/os.path.getsizeentry.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 效能優勢明顯。
  • Python 3.5+ 專案優先使用 os.scandir。
copyright © 萬盛學電腦網 all rights reserved