Python에서 파일 또는 디렉토리(폴더) 크기 가져오기

사업

Python 표준 라이브러리 os를 사용하여 파일의 크기(용량) 또는 디렉터리에 포함된 파일의 전체 크기를 얻을 수 있습니다.

다음 세 가지 방법을 설명합니다. 얻을 수 있는 크기의 단위는 모두 바이트입니다.

  • 파일 크기 가져오기: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()이 엔터티를 판단합니다. 따라서 기호 링크를 무시하려면 기호 링크에 대해 true를 반환하는 os.path.islink()와 함께 조건부 판단을 사용하십시오.

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