要递归地触摸所有文件,您需要使用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()