如何使用 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-02-18

745 次瀏覽

啟動你的 職業

完成課程後獲得認證

開始
廣告
© . All rights reserved.