파이썬에서 디렉토리 또는 파일 크기를 계산하는 방법을 소개합니다.
1. 파일 크기 계산 : os.path.getsize()
os.path.getsize()는 파일 경로를 인자로 전달하면, 그 파일의 용량을 리턴합니다. 파일 사이즈의 단위는 byte입니다.
import os
print(os.path.getsize("~/images/dog-4534463_1920.jpg"))Output:
324615터미널에서 ls -al로 용량을 확인하면 위의 출력 결과와 동일합니다.
$ ls -al
-rwxrwxrwx 1 js js 324615 10 18 2019 dog-4534463_1920.jpg2. 디렉토리 크기 계산 (Python 3.5 이상 버전)
Python 3.5 이상 버전에서는 os.scandir()으로 디렉토리의 파일 리스트를 가져올 수 있습니다.
아래와 같이 재귀적인 방법으로 디렉토리 하위의 모든 파일들의 사이즈를 계산할 수 있습니다.
import os
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
result = get_dir_size("~/images/")
print(result)Output:
134503743. 디렉토리 크기 계산 (Python 3.4 이하 버전)
Python 3.4 이하 버전에서는 os.listdir()으로 디렉토리의 파일 리스트를 가져올 수 있습니다.
아래와 같이 재귀적인 방법으로 디렉토리 하위의 모든 파일들의 사이즈를 계산할 수 있습니다.
import os
def get_dir_size(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
result = get_dir_size("~/images/")
print(result)Output:
134503744. 파일 또는 디렉토리 구분하지 않고 계산하는 함수
위에서 소개한 예제는 파일 크기를 계산하거나, 디렉토리 크기를 계산하는 예제입니다.
인자로 전달된 패스가 파일인지 디렉토리인지 구분하지 않고 사이즈를 계산하려면 아래 예제처럼 구현하시면 됩니다.
get_size() 함수에서 인자로 전달된 경로가 파일인지 디렉토리인지 구분하고, 만약 파일이라면 그 파일의 크기를 계산하고, 디렉토리라면 get_dir_size()를 호출하여 재귀적인 방법으로 하위 파일들의 크기를 계산하면 됩니다.
import os
def get_dir_size(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(full_path)
return total
def get_size(path='.'):
if os.path.isfile(path):
return os.path.getsize(path)
elif os.path.isdir(path):
return get_dir_size(path)
# file size
print(get_size("~/images/dog-4534463_1920.jpg"))
# directory size
print(get_size("~/images/"))Output:
324615
13450374References
Loading script...
Related Posts
- Python - Yaml 파일 파싱하는 방법
- Python - 파일 내용 삭제
- Python - for문에서 리스트 순회 중 요소 값 제거
- Python - 두 리스트에서 공통 요소 값 찾기
- Python - 문자열 앞(뒤)에 0으로 채우기
- Python - 공백으로 문자열 분리
- Python - 중첩 리스트 평탄화(1차원 리스트 변환)
- Python - 16진수 문자열을 Int로 변환
- Python - 두 날짜, 시간 비교
- Python f-string으로 변수 이름, 값 쉽게 출력 (변수명 = )
- Python - nonlocal과 global 사용 방법
- Python 바다코끼리 연산자 := 알아보기
- Python - pip와 requirements.txt로 패키지 관리
- Python - 딕셔너리 보기 좋게 출력 (pprint)
- Python - Requests 사용 방법 (GET/POST/PUT/PATCH/DELETE)
- Python - 온라인 컴파일러 사이트 추천
- Python - os.walk()를 사용하여 디렉토리, 파일 탐색
- Python - 문자열 비교 방법
- Python - Text 파일 읽고 쓰는 방법 (read, write, append)
- Python - 리스트에서 첫번째, 마지막 요소 가져오는 방법
- Python - 두개의 리스트 하나로 합치기
- Python - 리스트의 첫번째 요소 제거
- Python - 리스트의 마지막 요소 제거
- Python 소수점 버림, 4가지 방법
- Python 코드 안에서 버전 확인 방법
- Python 소수점 반올림, round() 예제
- Python - 리스트 평균 구하기, 3가지 방법
- Python - bytes를 String으로 변환하는 방법
- Python - String을 bytes로 변환하는 방법
- Python 버전 확인 방법 (터미널, cmd 명령어)
- Python - 람다(Lambda) 함수 사용 방법
- Python - dict 정렬 (Key, Value로 sorting)
- Python - range() 사용 방법 및 예제
- Python - 리스트를 문자열로 변환
- Python - 문자를 숫자로 변환 (String to Integer, Float)