SeouliteLab

[Python/파이썬] 디렉토리, 파일 사이즈 계산하기 본문

프로그래밍

[Python/파이썬] 디렉토리, 파일 사이즈 계산하기

Seoulite Lab 2024. 3. 4. 08:42

파이썬을 사용하면 디렉토리의 파일 크기를 계산하고 파일의 크기를 확인할 수 있습니다. 이를 통해 파일 시스템을 탐색하고 사용 중인 공간을 확인하는 데 도움이 됩니다. 아래 예제를 통해 디렉토리와 파일의 크기를 계산하는 방법을 살펴보겠습니다.

1. 디렉토리의 파일 크기 계산

특정 디렉토리의 모든 파일의 크기를 계산하는 함수를 작성해보겠습니다. 이 함수는 재귀적으로 모든 하위 디렉토리를 탐색하여 파일 크기를 합산합니다.

import os

def get_directory_size(directory):
    total_size = 0
    for path, dirs, files in os.walk(directory):
        for f in files:
            fp = os.path.join(path, f)
            total_size += os.path.getsize(fp)
    return total_size

# 디렉토리의 크기 계산 및 출력
directory_path = "/path/to/your/directory"
size_in_bytes = get_directory_size(directory_path)
print("디렉토리 크기:", size_in_bytes, "bytes")

위 코드에서는 os.walk() 함수를 사용하여 디렉토리를 재귀적으로 탐색하고, os.path.getsize() 함수를 사용하여 각 파일의 크기를 가져와서 합산합니다. 이렇게 계산된 디렉토리의 크기를 바이트 단위로 출력합니다.

2. 특정 파일의 크기 확인

특정 파일의 크기를 확인하는 방법도 간단합니다. os.path.getsize() 함수를 사용하여 파일의 크기를 가져올 수 있습니다.

import os

# 파일 경로 지정
file_path = "/path/to/your/file.txt"

# 파일 크기 확인
size_in_bytes = os.path.getsize(file_path)
print("파일 크기:", size_in_bytes, "bytes")

위 코드에서는 os.path.getsize() 함수를 사용하여 파일의 크기를 바이트 단위로 가져옵니다. 이렇게 가져온 파일의 크기를 출력합니다.