Python os.path.getmtime() 方法



Python 的 os.path.getmtime() 方法用於檢索檔案或目錄的最後修改時間。

該方法返回一個浮點數,表示指定路徑最近修改的時間,以自紀元(1970年1月1日,00:00:00 UTC)以來的秒數為單位。

如果指定的路徑不存在,或者存在阻止訪問路徑的許可權問題,則該方法分別引發 FileNotFoundErrorPermissionError

語法

以下是 Python os.path.getmtime() 方法的基本語法:

os.path.getmtime(path)

引數

此方法接受一個字串作為引數,表示要檢索其最後修改時間的檔案的路徑。

返回值

該方法返回一個浮點數,表示檔案上次修改時自紀元(1970年1月1日)以來的秒數。

示例

在下面的示例中,我們檢索位於給定路徑 "file_Path" 的檔案的最後修改時間,並以自紀元以來的秒數列印它:

import os
file_path = "/home/lenovo/documents/file.txt"
mtime = os.path.getmtime(file_path)
print("The file was modified at:",mtime)

輸出

獲得的輸出如下:

The file was accessed at: 1640227200.0

示例

這裡,我們檢索當前目錄的最後修改時間,並以自紀元以來的秒數列印它:

import os
current_dir = os.getcwd()
mtime = os.path.getmtime(current_dir)
print("The directory was modified at:",mtime) 

輸出

以下是上述程式碼的輸出:

The directory was modified at: 1713938293.186791

示例

此示例使用 Windows 系統上的 getmtime() 方法以人類可讀的格式檢索檔案最後修改時間:

import os
import time
file_path = "C:\\Users\\Lenovo\\Downloads\\sql.txt"
mtime = os.path.getmtime(file_path)
print(time.ctime(mtime))

輸出

我們得到如下所示的輸出:

Thu Sep 14 17:26:04 2023

示例

如果我們嘗試檢索不存在的檔案路徑的最後修改時間,則 getmtime() 方法會引發 "FileNotFoundError":

import os
link_path = "/non/existent/path"
mtime = os.path.getmtime(link_path)
print("The path was modified at:",mtime)      

輸出

產生的結果如下所示:

Traceback (most recent call last):
  File "C:\Users\Lenovo\Desktop\untitled.py", line 3, in <module>
    mtime = os.path.getmtime(link_path)
  File "<frozen genericpath>", line 67, in getmtime
FileNotFoundError: [WinError 3] The system cannot find the path specified: '/non/existent/path'
os_path_methods.htm
廣告
© . All rights reserved.