Python os.utime() Method



The Python method utime() of OS module allows us to set the access and modification times of the file specified by path.

NOTE: The last access time and the last modification time of a file are represented by st_atime_ns and st_mtime_ns arguments respectively of "os.stat()".

Syntax

Syntax of Python os.utime() method is shown below −

os.utime(path, times, *, [ns, ]dir_fd, follow_symlinks)

Parameters

The Python os.utime() method accepts two parameters which are as follows −

  • path − This is the path of the file.

  • times − This is the file access and modified time. If times is none, then the file access and modified times are set to the current time. The parameter times consists of row in the form of atime & mtime that represents accesstime and modifiedtime respectively.

  • ns − This parameter represents an optional 2-tuple (atime_ns, mtime_ns). It is similar to "times" argument but with nanosecond precision.

  • dir_fd − An optional file descriptor referring to a directory.

  • follow_symlinks − A boolean that decides whether to follow symbolic links or not.

Return Value

The utime() method of Python OS module does not return any value.

Example

The following example shows the usage of utime() method. Here, we are displaying stat information and then, modifying atime and mtime.

import os, sys

# Showing stat information of file
stinfo = os.stat("atty.py")
print (stinfo)

# Using os.stat to recieve atime and mtime of file
print ("access time of a2.py: %s" %stinfo.st_atime)
print ("modified time of a2.py: %s" %stinfo.st_mtime)

# Modifying atime and mtime
os.utime("atty.py",(1330712280, 1330712292))
print ("Modification done!!")

When we run above program, it produces following result −

os.stat_result(st_mode=33204, st_ino=1054960, st_dev=2051,
 st_nlink=1, st_uid=1000, st_gid=1000, st_size=234, 
 st_atime=1713163636, st_mtime=1713163633, st_ctime=1713163633)
access time of a2.py: 1713163636.657509
modified time of a2.py: 1713163633.4790993

Modification done!!
python_files_io.htm
Advertisements