본문으로 건너뛰기

Python - 파일 크기 확인

파이썬에서 파일, 디렉토리(폴더) 크기를 확인하는 방법에 대해서 알아보겠습니다.

1. 파일 크기 확인

os.path.getsize(file_path)file_path의 크기를 바이트 단위로 리턴합니다.

이 함수를 이용하여 아래와 같이 파일의 크기를 계산할 수 있습니다. 이 예제는 /tmp/aaa.txt 파일의 크기를 가져오는 예제입니다.

import os

def get_file_size(file_path):
try:
# 파일 크기를 바이트 단위로 가져옴
file_size = os.path.getsize(file_path)
return file_size
except FileNotFoundError:
print(f"파일을 찾을 수 없습니다: {file_path}")
except Exception as e:
print(f"파일 크기를 가져오는 중 오류가 발생했습니다: {e}")


file_path = '/tmp/aaa.txt'
file_size = get_file_size(file_path)
if file_size is not None:
print(f"{file_path}의 크기: {file_size} 바이트")

실행 결과

/tmp/aaa.txt의 크기: 7 바이트

2. 디렉토리(폴더) 크기 확인

디렉토리는 하위에 파일과 디렉토리 등을 갖고 있습니다. 하위 경로를 모두 탐색하면서 파일의 크기를 계산하면 디렉토리의 크기를 계산할 수 있습니다.

아래 두개 함수를 이용하여, 아래 예제와 같이 특정 디렉토리(예제에서는 /home/js/test)의 크기를 계산할 수 있습니다. 참고로, 예제는 바이트 단위의 크기를 MB 단위로 변환하였습니다.

  • os.walk(directory_path) : directory_path 경로 하위의 파일들을 반복문으로 순회합니다. for문 안에서 모든 하위 파일들의 이름과 경로를 알 수 있습니다.
  • os.path.getsize() : for문에서 파일들을 순회하면서 크기를 계산할 수 있습니다.
import os

def get_human_readable_size(size_in_bytes):
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
if size_in_bytes < 1024:
return f"{size_in_bytes:.2f} {unit}"
size_in_bytes /= 1024

def get_directory_info(directory_path):
total_size = 0
total_files = 0
total_subdirs = 0

for dirpath, dirnames, filenames in os.walk(directory_path):
total_subdirs += len(dirnames)
for filename in filenames:
file_path = os.path.join(dirpath, filename)
total_size += os.path.getsize(file_path)
total_files += 1

return total_size, total_files, total_subdirs


directory_path = '/home/js/test'
directory_size, file_count, subdir_count = get_directory_info(directory_path)
print(f"{directory_path}의 크기: {get_human_readable_size(directory_size)}")
print(f"파일 수: {file_count}")
print(f"하위 디렉토리 수: {subdir_count}")

실행 결과

/home/js/test의 크기: 885.83 MB
파일 수: 11622
하위 디렉토리 수: 2373