Python os.path.getatime() 方法



Python 的 os.path.getatime() 方法用於檢索檔案或目錄的最後訪問時間。

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

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

語法

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

os.path.getatime(path)

引數

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

返回值

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

示例

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

import os
file_path = "/home/lenovo/documents/file.txt"
atime = os.path.getatime(file_path)
print("The file was accessed at:",atime)

輸出

獲得的輸出如下:

The file was accessed at: 1640227200.0

示例

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

import os
current_dir = os.getcwd()
atime = os.path.getatime(current_dir)
print("The directory was accessed at:",atime)   

輸出

以上程式碼的輸出如下:

The directory was accessed at: 1714131137.8021567

示例

此示例使用 getatime() 方法以人類可讀的格式檢索 Windows 系統上指定檔案路徑的最後訪問時間:

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

輸出

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

Fri Apr 26 18:30:51 2024

示例

如果我們嘗試檢索不存在的檔案路徑的最後訪問時間,getatime() 方法會引發“FileNotFoundError”:

import os
link_path = "/non/existent/path"
atime = os.path.getatime(link_path)
print("The path was accessed at:",atime)       

輸出

產生的結果如下所示:

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