How to touch all the files recursively using Python?

In file system management, it's sometimes necessary to update the modification or access time of files which is commonly referred as "touching" files. This is useful in automation scripts, build systems or cache invalidation mechanisms. Python offers powerful modules such as os and pathlib to touch all files within a directory recursively.

In this article, we'll explore different methods to recursively touch files using Python by ensuring each file's timestamp is refreshed as needed.

Using os.walk() and os.utime()

The os.walk() function generates the file names in a directory tree by walking the tree either top-down or bottom-up. It can be combined with os.utime() to update file timestamps.

Example

In this example, we will use os.walk() and os.utime() to touch all files recursively ?

import os
import time

# Create sample directory structure for demonstration
os.makedirs("demo_dir/subdir", exist_ok=True)
with open("demo_dir/file1.txt", "w") as f:
    f.write("Sample content")
with open("demo_dir/subdir/file2.txt", "w") as f:
    f.write("Another file")

# Define the root directory
root_dir = "demo_dir"

# Get current time
current_time = time.time()

# Walk through all subdirectories
for dirpath, _, filenames in os.walk(root_dir):
    for file in filenames:
        full_path = os.path.join(dirpath, file)
        print(f"Touching: {full_path}")
        # Update access and modification time
        os.utime(full_path, (current_time, current_time))

print("All files touched successfully!")
Touching: demo_dir/file1.txt
Touching: demo_dir/subdir/file2.txt
All files touched successfully!

Using pathlib.Path.rglob()

The pathlib module provides a modern way to interact with the filesystem. With Path.rglob(), we can recursively iterate over all files matching a pattern and touch them.

Example

In this example, we are using the Path.rglob() method to touch all files recursively ?

from pathlib import Path
import time

# Create sample directory structure
Path("demo_path/nested/deep").mkdir(parents=True, exist_ok=True)
Path("demo_path/file1.py").write_text("# Python file")
Path("demo_path/nested/file2.txt").write_text("Text file")
Path("demo_path/nested/deep/file3.log").write_text("Log file")

# Define the root directory
root = Path("demo_path")
current_time = time.time()

# Iterate through all files recursively
for file in root.rglob('*'):
    if file.is_file():
        print(f"Touching: {file}")
        file.touch(times=(current_time, current_time))

print("All files touched using pathlib!")
Touching: demo_path/file1.py
Touching: demo_path/nested/file2.txt
Touching: demo_path/nested/deep/file3.log
All files touched using pathlib!

Creating Non-existent Files

To mimic Unix touch command behavior where missing files are created, we can add a check and create the file if it doesn't exist ?

from pathlib import Path
import time

# Create sample structure
Path("touch_demo/existing").mkdir(parents=True, exist_ok=True)
Path("touch_demo/existing/real_file.txt").write_text("Existing file")

# Define files to touch (some exist, some don't)
files_to_touch = [
    "touch_demo/existing/real_file.txt",
    "touch_demo/new_file.txt", 
    "touch_demo/existing/another_new.txt"
]

current_time = time.time()

for file_path in files_to_touch:
    path = Path(file_path)
    
    # Create parent directories if needed
    path.parent.mkdir(parents=True, exist_ok=True)
    
    if not path.exists():
        print(f"Creating: {path}")
        path.touch()  # Create empty file
    else:
        print(f"Updating timestamp: {path}")
    
    # Update timestamp
    path.touch(times=(current_time, current_time))

print("Touch operation completed!")
Updating timestamp: touch_demo/existing/real_file.txt
Creating: touch_demo/new_file.txt
Creating: touch_demo/existing/another_new.txt
Touch operation completed!

Comparison of Methods

Method Python Version Best For Creates Missing Files
os.walk() + os.utime() All versions Legacy code, fine control No
pathlib.rglob() 3.4+ Modern Python, clean syntax Optional with touch()
Unix-style touch 3.4+ Mimicking shell behavior Yes

Conclusion

Use pathlib.Path.rglob() for modern Python applications as it provides cleaner syntax. Use os.walk() for legacy compatibility or when you need fine-grained control over the file traversal process.

Updated on: 2026-03-24T18:30:50+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements