在 Python 中獲取文件或目錄(文件夾)的大小

商業

使用 Python 標準庫 os,可以獲取文件的大小(容量)或目錄中包含的文件的總大小。

下面介紹三種方法。可以獲取的size單位都是字節。

  • 獲取文件大小:os.path.getsize()
  • 通過組合以下函數(Python 3.5 或更高版本)獲取目錄的大小:os.scandir()
  • 結合以下函數獲取目錄的大小(Python 3.4 及更早版本):os.listdir()

獲取文件大小:os.path.getsize()

文件的大小(容量)可以通過 os.path.getsize() 獲取。

給出要獲取其大小的文件的路徑作為參數。

import os

print(os.path.getsize('data/src/lena_square.png'))
# 473831

獲取目錄(文件夾)的大小:os.scandir()

要計算目錄(文件夾)中包含的文件的總大小,請使用 os.scandir()。

該函數是在 Python 3.5 中添加的,因此早期版本使用 os.listdir()。 os.listdir() 示例稍後描述。

定義一個函數如下。

def get_dir_size(path='.'):
    total = 0
    with os.scandir(path) as it:
        for entry in it:
            if entry.is_file():
                total += entry.stat().st_size
            elif entry.is_dir():
                total += get_dir_size(entry.path)
    return total

print(get_dir_size('data/src'))
# 56130856

os.scandir() 返回 os.DirEntry 對象的迭代器。

DirEntry 對象,使用 is_file() 和 is_dir() 方法判斷是文件還是目錄。如果是文件,則從 stat_result 對象的 st_size 屬性中獲取大小。在目錄的情況下,遞歸調用此函數以將所有大小相加並返回總大小。

此外,默認情況下,is_file() 對文件的符號鏈接返回 TRUE。此外,is_dir() 對目錄的符號鏈接返回 true。如果要忽略符號鏈接,請將 is_file() 和 is_dir() 的 follow_symlinks 參數設置為 false。

另外,如果您不需要遍歷子目錄,您可以刪除以下部分。

            elif entry.is_dir():
                total += get_dir_size(entry.path)

如果文件的路徑作為參數傳遞,上述函數將失敗。如果你需要一個函數來返回文件或目錄的大小,你可以寫如下。

def get_size(path='.'):
    if os.path.isfile(path):
        return os.path.getsize(path)
    elif os.path.isdir(path):
        return get_dir_size(path)

print(get_size('data/src'))
# 56130856

print(get_size('data/src/lena_square.png'))
# 473831

獲取目錄(文件夾)的大小:os.listdir()

Python 3.4 或更早版本沒有 os.scandir(),所以使用 os.listdir()。

定義一個函數如下。

def get_dir_size_old(path='.'):
    total = 0
    for p in os.listdir(path):
        full_path = os.path.join(path, p)
        if os.path.isfile(full_path):
            total += os.path.getsize(full_path)
        elif os.path.isdir(full_path):
            total += get_dir_size_old(full_path)
    return total

print(get_dir_size_old('data/src'))
# 56130856

基本思想與 os.scandir() 的情況相同。

使用 os.listdir() 可以獲得的是文件名(目錄名)列表。使用 os.path.join() 將每個文件名或目錄名與父目錄的路徑連接起來以創建完整路徑。

如果目標是符號鏈接,os.path.isfile() 和 os.path.isdir() 將判斷實體。所以,如果要忽略符號鏈接,結合os.path.islink()使用條件判斷,對符號鏈接返回true。

和 os.scandir() 的情況一樣,如果不需要遍歷子目錄,只需刪除以下部分即可。

        elif os.path.isdir(full_path):
            total += get_dir_size_old(full_path)

如果文件的路徑作為參數傳遞,上述函數將失敗。如果你需要一個函數來返回文件或目錄的大小,你可以寫如下。

def get_size_old(path='.'):
    if os.path.isfile(path):
        return os.path.getsize(path)
    elif os.path.isdir(path):
        return get_dir_size_old(path)

print(get_size_old('data/src'))
# 56130856

print(get_size_old('data/src/lena_square.png'))
# 473831
Copied title and URL