Python os.path.getsize() 方法



Python 的 os.path.getsize() 方法用於以位元組為單位檢索檔案的大小。它返回一個整數,表示指定檔案的大小。

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

語法

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

os.path.getsize(path)

引數

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

返回值

該方法返回一個整數,表示檔案的大小(以位元組為單位)。

示例

在以下示例中,我們正在檢索位於給定路徑 "file_Path" 的檔案的大小(以位元組為單位):

import os
file_path = "/home/lenovo/documents/file.txt"
size = os.path.getsize(file_path)
print("The size of the file is:",size)

輸出

獲得的輸出如下:

The size of the file is: 873

示例

這裡,我們正在檢索當前目錄的大小並以位元組為單位列印它:

import os
current_dir = os.getcwd()
size = os.path.getsize(current_dir)
print("The size of the current directory is:",size)

輸出

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

The size of the current directory is: 16384

示例

此示例檢索位於 "/home/lenovo/symlink" 的符號連結的大小並以位元組為單位列印它:

import os
link_path = "/home/lenovo/symlink"
size = os.path.getsize(link_path)
print("The size of the symbolic link is:",size)  

輸出

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

The size of the symbolic link is: 53

示例

如果我們嘗試檢索不存在的檔案路徑 "/non/existent/path" 的大小,則 getsize() 方法會引發 "FileNotFoundError":

import os
link_path = "/non/existent/path"
size = os.path.getsize(link_path)
print("The size of the file is:",size)    

輸出

產生的結果如下所示:

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

© . All rights reserved.