[python] 파이썬을 사용하여 디렉토리의 크기를 계산합니까?

이 특정 바퀴를 다시 발명하기 전에 파이썬을 사용하여 디렉토리의 크기를 계산하는 데 좋은 루틴을 가진 사람이 있습니까? 루틴이 크기를 Mb / Gb 등으로 멋지게 포맷하면 매우 좋을 것입니다.



답변

이것은 모든 하위 디렉토리를 걷는다; 합산 파일 크기 :

import os

def get_size(start_path = '.'):
    total_size = 0
    for dirpath, dirnames, filenames in os.walk(start_path):
        for f in filenames:
            fp = os.path.join(dirpath, f)
            # skip if it is symbolic link
            if not os.path.islink(fp):
                total_size += os.path.getsize(fp)

    return total_size

print(get_size(), 'bytes')

os.listdir을 사용하는 재미를위한 oneliner ( 하위 디렉토리는 포함하지 않음 ) :

import os
sum(os.path.getsize(f) for f in os.listdir('.') if os.path.isfile(f))

참고:

업데이트
사용에 os.path.getsize , 이것은 os.stat (). st_size 방법을 사용하는 것보다 더 명확하다.

이것을 지적 해준 ghostdog74에게 감사합니다!

os.statst_size 크기를 바이트 단위로 제공합니다. 파일 크기 및 기타 파일 관련 정보를 얻는 데 사용될 수도 있습니다.

import os

nbytes = sum(d.stat().st_size for d in os.scandir('.') if d.is_file())

2018 업데이트

Python 3.4 또는 이전 버전을 사용하는 경우 walk타사 scandir패키지 에서 제공 하는보다 효율적인 방법을 사용하는 것이 좋습니다. Python 3.5 이상에서이 패키지는 표준 라이브러리에 통합되었으며os.walk 이에 따라 성능이 향상되었습니다.

2019 업데이트

최근에 pathlib점점 더 많이 사용 하고 있으며 pathlib해결책은 다음과 같습니다.

from pathlib import Path

root_directory = Path('.')
sum(f.stat().st_size for f in root_directory.glob('**/*') if f.is_file())


답변

지금까지 제안 된 접근법 중 일부는 재귀를 구현하고 다른 접근법은 쉘을 사용하거나 깔끔한 형식의 결과를 생성하지 않습니다. 코드가 Linux 플랫폼에서 일회성 인 경우 평소처럼 재귀가 포함 된 한 줄짜리 서식을 지정할 수 있습니다. print마지막 줄에서를 제외하고 현재 버전의 python2및에서 작동합니다 python3.

du.py
-----
#!/usr/bin/python3
import subprocess

def du(path):
    """disk usage in human readable format (e.g. '2,1GB')"""
    return subprocess.check_output(['du','-sh', path]).split()[0].decode('utf-8')

if __name__ == "__main__":
    print(du('.'))

간단하고 효율적이며 파일 및 다중 레벨 디렉토리에서 작동합니다.

$ chmod 750 du.py
$ ./du.py
2,9M


답변

다음은 “du -sb”를 실행할 때와 정확히 동일한 바이트를 반환하는 재귀 함수 (모든 하위 폴더와 해당 파일의 크기를 재귀 적으로 합한 것)입니다. 리눅스에서 ( “.”는 “현재 폴더”를 의미합니다) :

import os

def getFolderSize(folder):
    total_size = os.path.getsize(folder)
    for item in os.listdir(folder):
        itempath = os.path.join(folder, item)
        if os.path.isfile(itempath):
            total_size += os.path.getsize(itempath)
        elif os.path.isdir(itempath):
            total_size += getFolderSize(itempath)
    return total_size

print "Size: " + str(getFolderSize("."))


답변

파이썬 3.5 재귀 폴더 크기 os.scandir

def folder_size(path='.'):
    total = 0
    for entry in os.scandir(path):
        if entry.is_file():
            total += entry.stat().st_size
        elif entry.is_dir():
            total += folder_size(entry.path)
    return total


답변

monknut 응답은 좋지만 symlink가 끊어지면 실패 하므로이 경로가 실제로 존재하는지 확인해야합니다

if os.path.exists(fp):
    total_size += os.stat(fp).st_size


답변

허용되는 답변은 하드 링크 또는 소프트 링크를 고려하지 않으며 해당 파일을 두 번 계산합니다. 본 inode를 추적하고 해당 파일의 크기를 추가하지 않으려 고합니다.

import os
def get_size(start_path='.'):
    total_size = 0
    seen = {}
    for dirpath, dirnames, filenames in os.walk(start_path):
        for f in filenames:
            fp = os.path.join(dirpath, f)
            try:
                stat = os.stat(fp)
            except OSError:
                continue

            try:
                seen[stat.st_ino]
            except KeyError:
                seen[stat.st_ino] = True
            else:
                continue

            total_size += stat.st_size

    return total_size

print get_size()


답변

Chris의 대답은 좋지만 보이는 디렉토리를 확인하기 위해 세트를 사용하여 관용적으로 만들 수 있으며 제어 흐름에 예외를 사용하지 않아도됩니다.

def directory_size(path):
    total_size = 0
    seen = set()

    for dirpath, dirnames, filenames in os.walk(path):
        for f in filenames:
            fp = os.path.join(dirpath, f)

            try:
                stat = os.stat(fp)
            except OSError:
                continue

            if stat.st_ino in seen:
                continue

            seen.add(stat.st_ino)

            total_size += stat.st_size

    return total_size  # size in bytes