Python os.path.getctime() 方法



Python 的 os.path.getctime() 方法用於獲取檔案或目錄的建立時間。建立時間表示檔案或目錄的元資料最後一次更改的時間。這包括對檔案許可權、所有權或其他元資料的更改,以及建立時間。

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

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

語法

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

os.path.getctime(path)

引數

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

返回值

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

示例

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

import os
file_path = "/home/lenovo/documents/file.txt"
ctime = os.path.getctime(file_path)
print("The file was created at:",ctime)

輸出

獲得的輸出如下:

The file was created at: 1640227200.0

示例

在這裡,我們檢索當前目錄的建立時間,並以自紀元以來的秒數列印它:

import os
current_dir = os.getcwd()
ctime = os.path.getctime(current_dir)
print("The directory was created at:",ctime) 

輸出

以上程式碼的輸出如下:

The directory was created at: 1656958586.0913115

示例

此示例使用 getctime() 方法以人類可讀的格式檢索 Windows 系統上指定檔案位置的建立時間:

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

輸出

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

Thu Sep 14 17:25:33 2023

示例

如果我們嘗試檢索不存在的檔案路徑的建立時間,getctime() 方法將引發“FileNotFoundError”:

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

輸出

產生的結果如下所示:

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