Update Last Modified Time of File in Python

Python – Update last modified time of file

To update the last modified time of a file in Python, you can use the os.utime()function. Import os library, call the os.utime() function and pass the file path and new time as arguments.

The syntax to call os.utime() to update the modified time of a file is

os.utime('path/to/file', (new_time, new_time))

Note: The 'path/to/file' in the above expression should be replaced with the actual path of the file you want to check.

Example

In the following program, we update the modified time of the file myfolder/sample.txt to current time.

File

Update Last Modified Time of File in Python

Python Program

import os
import time

path_to_file = "myfolder/sample.txt"
current_time = time.time()

os.utime(path_to_file, (current_time, current_time))
print('Last modified time of file is updated.')
Copy

Output

Last modified time of file is updated.

Summary

In this tutorial of Python Examples, we learned how to update last modified time of a file using os.utime() function.

Related Tutorials

Code copied to clipboard successfully 👍