
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 approach or bottom-up approach. It can be combined with os.utime() to update file timestamps.
Example
In this example, we will use the function os.walk() and os.utime() to touch all the files recursively ?
import os import time # Define the root directory root_dir = r'D:\Tutorialspoint' # 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) # Update access and modification time os.utime(full_path, (current_time, current_time))
When we execute the above program, then it will update timestamps of all files within the given directory and its subdirectories.
Using pathlib.Path.rglob()
The pathlib module provides a best way to interact with the filesystem. With Path.rglob(), we can recursively iterate over all files matching a given pattern and touch them.
Example
In this example, we are using the Path.rglob() method of the pathlib module to touch all files recursively ?
from pathlib import Path import os import time # Define the root directory root = Path(r'D:\Tutorialspoint') current_time = time.time() # Iterate through all files recursively for file in root.rglob('*'): if file.is_file(): os.utime(file, (current_time, current_time))
This method is concise and works well for modern Python versions.
Creating Non-existent Files
If we want to mimic the behavior of Unix then we can use the touch command where missing files are created, add a check and create the file if it doesn't exist. Here is the example which shows how to create Non-existent Files ?
from pathlib import Path import os import time # Define the root directory root = Path(r'D:\Tutorialspoint') current_time = time.time() # Recursively process all paths for path in root.rglob('*'): if path.is_dir(): continue elif not path.exists(): # Create an empty file path.touch() # Touch the file (update timestamp) os.utime(path, (current_time, current_time))