Python os.utime() 方法



Python 的 utime() 方法 (OS 模組) 允許我們設定由 path 指定的檔案的訪問時間和修改時間。

注意: 檔案的最後訪問時間和最後修改時間分別由 "os.stat()" 的 st_atime_nsst_mtime_ns 引數表示。

語法

Python os.utime() 方法的語法如下所示:

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

引數

Python os.utime() 方法接受兩個引數,如下所示:

  • path - 這是檔案的路徑。

  • times - 這是檔案的訪問時間和修改時間。如果 times 為 None,則檔案的訪問時間和修改時間將設定為當前時間。引數 times 包含一個以 atime 和 mtime 形式的行,分別表示訪問時間和修改時間。

  • ns - 此引數表示一個可選的 2 元組 (atime_ns, mtime_ns)。它類似於 "times" 引數,但具有納秒精度。

  • dir_fd - 指向目錄的可選檔案描述符。

  • follow_symlinks - 一個布林值,決定是否跟隨符號連結。

返回值

Python OS 模組的 utime() 方法不返回值。

示例

以下示例顯示了 utime() 方法的使用。在這裡,我們首先顯示 stat 資訊,然後修改 atime 和 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!!")

當我們執行上述程式時,它會產生以下結果:

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
廣告

© . All rights reserved.