How to touch all the files recursively using Python?

PythonServer Side ProgrammingProgramming

To touch all the  files recursively, you need to walk the directory tree using os.walk and add touch all the files in it using os.utime(path_to_file). 

example

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))

In Python 3.4+, you can directly use the pathlib module to touch files. 

 example

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()
raja
Published on 27-Dec-2017 15:16:26
Advertisements