Home > Article > Backend Development > How Can I Calculate Directory Size Using Python?
Calculating Directory Size with Python: Unveiling a Comprehensive Solution
Estimating the size of a directory is a common task in programming. Python, with its robust standard library, provides various approaches to tackle this issue.
One method employs the os.walk() function. It traverses the directory tree, accumulates file sizes, and displays the result in a human-readable format:
<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) if not os.path.islink(fp): total_size += os.path.getsize(fp) return total_size print(get_size(), 'bytes')</code>
Alternatively, a more concise approach using os.listdir() excludes subdirectories:
<code class="python">import os sum(os.path.getsize(f) for f in os.listdir('.') if os.path.isfile(f))</code>
For more granular information, os.stat() offers both file and directory statistics. The st_size attribute provides the file size in bytes:
<code class="python">import os nbytes = sum(d.stat().st_size for d in os.scandir('.') if d.is_file())</code>
Python's recent versions include the pathlib module. Its solution combines functionality from both os and os.path:
<code class="python">from pathlib import Path root_directory = Path('.') sum(f.stat().st_size for f in root_directory.glob('**/*') if f.is_file())</code>
These techniques efficiently quantify directory size in Python. Whether selecting os.walk, os.listdir, os.stat, or pathlib, programmers can choose the most suitable method based on their requirements.
The above is the detailed content of How Can I Calculate Directory Size Using Python?. For more information, please follow other related articles on the PHP Chinese website!