Home  >  Article  >  Backend Development  >  How to Efficiently Calculate Directory Size in Python?

How to Efficiently Calculate Directory Size in Python?

Susan Sarandon
Susan SarandonOriginal
2024-11-01 14:50:28276browse

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:

<code class="python">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</code>

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.

The above is the detailed content of How to Efficiently Calculate Directory Size in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn