Home  >  Article  >  Backend Development  >  How to Calculate Directory Sizes in Python: A Comparison of Methods

How to Calculate Directory Sizes in Python: A Comparison of Methods

Susan Sarandon
Susan SarandonOriginal
2024-11-01 14:03:02955browse

How to Calculate Directory Sizes in Python: A Comparison of Methods

Calculating the Size of a Directory with Python

Before embarking on a custom implementation, it's worth exploring whether existing solutions can streamline the task of determining a directory's size.

Proposed Solution Using os.walk

The following Python routine adeptly walks through sub-directories and accumulates the sizes of each file:

<code class="python">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 symbolic links
            if not os.path.islink(fp):
                total_size += os.path.getsize(fp)
    return total_size

print(get_size(), 'bytes')</code>

Alternative One-Liner Using os.listdir

For a quicker and simpler approach that excludes sub-directories, consider the following one-liner:

<code class="python">import os
sum(os.path.getsize(f) for f in os.listdir('.') if os.path.isfile(f))</code>

References and Further Optimizations

For more information, refer to the following resources:

  • os.path.getsize: Acquires file sizes in bytes
  • os.path.islink: Detects symbolic links
  • os.path.stat().st_size: An alternative file size retrieval method
  • The scandir package: Offers an efficient walk method
  • The pathlib module: For a more concise and versatile solution

By opting for pre-existing code, you can expedite your development process while ensuring accuracy in calculating directory sizes.

The above is the detailed content of How to Calculate Directory Sizes in Python: A Comparison of Methods. 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