如何使用 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()
廣告
© .
All rights reserved.