파이썬 디렉토리 용량 구하기

조회수 1456회

파이썬에서 디렉토리의 용량을 구하는 방법이 있을까요?
파일 크기를 구하듯이 os.path.getsize() 를 사용하면 디렉토리의 용량이 구해질 줄 알았는데 용량이 모두 0으로 나옵니다. 디렉토리 전체 용량을 구하는 코드를 써 주실 분이 계신가요?

윈도우 10과 Python 3.8 사용 중입니다.

감사합니다!

  • (•́ ✖ •̀)
    알 수 없는 사용자

1 답변

  • 참고/코드 링크

    import os
    print(os.path.getsize("example.jpg"))
    

    위 코드로 파일의 용량을 구하실 수 있고요

    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
    
    

    이렇게 해서 get_dir_size(경로)로 얻을 수도 있습니다!

    #예시
    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
    
    dir = input("디렉토리 경로를 입력하세요")
    print(get_dir_size(path=dir))
    

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)