Python 3 – os.utime() Method
In Python 3, the os module provides various functions that can be used to interact with the operating system. One of the functions is the os.utime() method, which is used to change the access and modification times of a file.
In this article, we will take a closer look at the os.utime() method and explore how it can be used in Python code.
Syntax
The syntax for the os.utime() method is as follows:
os.utime(path, times=None, *, ns=False, dir_fd=None, follow_symlinks=True)
Here, the path
parameter is the path to the file whose access and modification times are to be changed.
The times
parameter is a tuple of two values representing the new access and modification times of the file. The values can be either numbers (in seconds since the epoch) or None.
If the times
parameter is None, then the file’s access and modification times are set to the current system time.
The ns
parameter is a Boolean value that indicates whether the times
parameter is in nanoseconds or not.
The dir_fd
parameter is an optional file descriptor referring to a directory. If dir_fd
is not None, then path
must be a relative path.
The follow_symlinks
parameter is a Boolean value that indicates whether to follow symbolic links or not.
Example
Here is an example that demonstrates the use of the os.utime() method:
import os
import time
# Set the modification time of a file to the current system time
path = 'my_file.txt'
os.utime(path)
# Get the current access and modification times of the file
access_time = os.path.getatime(path)
mod_time = os.path.getmtime(path)
# Print the access and modification times
print('Access time:', time.ctime(access_time))
print('Modification time:', time.ctime(mod_time))
In this example, we first import the os
and time
modules. Then, we use the os.utime()
method to set the modification time of the file “my_file.txt” to the current system time.
We then use the os.path.getatime()
and os.path.getmtime()
methods to retrieve the access and modification times of the file.
Finally, we use the time.ctime()
method to convert the access and modification times from seconds since the epoch to a more readable format, and print them to the console.
Conclusion
The os.utime() method is a useful tool when working with files in Python. By using this method, you can change the access and modification times of a file, which can be useful for a variety of reasons.
In this article, we learned how to use the os.utime() method in Python 3. We explored the syntax of the method, and looked at a simple example that demonstrated its use.
With this knowledge, you should be able to use the os.utime() method in your own Python programs to change the access and modification times of files as needed. Happy coding!