"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Efficiently Calculate Directory Size in Python?

How to Efficiently Calculate Directory Size in Python?

Published on 2024-11-09
Browse:213

How to Efficiently Calculate Directory Size in Python?

Directing Directory Size Calculation with Python

To gauge the space occupancy of a directory, Python offers several approaches. Below we delve into an efficient and comprehensive solution:

import os

def directory_size(start_path):
    total_size = 0

    for root, directories, files in os.walk(start_path):
        for file in files:
            file_path = os.path.join(root, file)
            if not os.path.islink(file_path):
                total_size  = os.path.getsize(file_path)

    return total_size

Advantages of this Solution:

  • Recursively traverses all subdirectories, ensuring comprehensive size calculation.
  • Excludes symbolic links, which may point to files outside the directory.
  • Calculates size in bytes, the fundamental unit of storage.

Additional Considerations:

  • To format the size in megabytes (MB) or gigabytes (GB), use round(total_size / 1024 ** 2, 2) for MB or round(total_size / 1024 ** 3, 2) for GB.
  • To exclude hidden files, add if file[0] != '.' before total_size = os.path.getsize(file_path) within the loop.
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3