如何使用 Python 遞迴地遍歷所有檔案?


要遞迴遍歷所有檔案,你需要使用 os.walk 遍歷目錄樹,並使用 os.utime(path_to_file) 遍歷其中的所有檔案。

示例

import os
# Recursively walk the tree
for root, dirs, files in os.walk(path):
    for file in files:
        # Set utime to current time
        os.utime(os.path.join(root, file))

在 Python 3.4+ 中,你可以直接使用 pathlib 模組來遍歷檔案。

示例

from pathlib import Path
import os
# Recursively walk the tree
for root, dirs, files in os.walk(path):
    for file in files:
        Path(os.path.join(root, file)).touch()

更新時間: 2020 年 2 月 18 日

746 次瀏覽

開啟你的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.