How to Efficiently Calculate Directory Size in Python?

Susan Sarandon
Release: 2024-11-01 14:50:28
Original
286 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!