파이썬에서 디렉토리 또는 파일 크기를 계산하는 방법을 소개합니다.
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.jpg
2. 디렉토리 크기 계산 (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:
13450374
3. 디렉토리 크기 계산 (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:
13450374
4. 파일 또는 디렉토리 구분하지 않고 계산하는 함수
위에서 소개한 예제는 파일 크기를 계산하거나, 디렉토리 크기를 계산하는 예제입니다.
인자로 전달된 패스가 파일인지 디렉토리인지 구분하지 않고 사이즈를 계산하려면 아래 예제처럼 구현하시면 됩니다.
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
13450374
References
Loading script...
Related Posts
- Python 소수점 반올림, round() 예제
- Python - String isdigit(), 문자열이 숫자인지 확인
- Python 소수점 버림, 4가지 방법
- 파이썬 주석 처리, 단축키 소개
- Python - Text 파일 읽고 쓰는 방법 (read, write, append)
- Python - String Formatting의 다양한 방법 정리(%, Str formatting, f-stirng)
- Python - os.path.join(), 폴더와 파일명으로 Path 생성
- Python - 파일을 읽고 한 줄씩 리스트에 저장
- Python - 문자열에서 줄바꿈(\n) 제거, 3가지 방법
- Python - Switch Case 구현 방법 (Match Case)
- 우분투에 Python 3.10 설치하는 방법
- Python - 문자열에서 특정 문자 제거, 3가지 방법
- Python - 함수 정의 및 호출 방법
- Python - 딕셔너리 초기화, 4가지 방법
- Python - input() 함수로 데이터 입력 받기
- Python - Tuple 사용 방법
- Python - 딕셔너리 정리 및 예제
- Python - String startswith(), 어떤 문자열로 시작하는지 확인
- Python - 날짜에서 월 이름 가져오기(숫자 -> 영어 이름 변환)
- Python - 어떤 날짜가 몇 주차인지 확인
- Python - D-Day 계산, 몇일 남았는지 날짜 세기
- Python - 날짜가 무슨 요일인지 계산
- Python - 어떤 날짜가 주말인지, 평일인지 확인
- Python - XML 생성 및 파일 저장
- Python - 특정 월의 시작 날짜, 마지막 날짜 얻기
- Python - XML 파싱, 태그 또는 요소 별로 읽기
- Python 버전 확인 방법 (터미널, cmd 명령어)
- Python - Selenium에서 웹페이지의 제목 가져오는 방법
- Python - 디렉토리, 파일 사이즈 계산
- Python 버전 확인 방법 (스크립트 또는 Command line)
- Python - 함수에서 두개 이상의 값 리턴
- Python - CSV 파일 읽기, 쓰기
- Python - 코드 실행 시간 측정
- Python - 반복문으로 리스트 순회 방법 (+ Index 출력)
- Python - with로 파일 열고 닫기