Home >Backend Development >Python Tutorial >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:
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!