How to touch all the files recursively using Python?


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

Updated on: 18-Feb-2020

571 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements