Calculating Directory Size with Python
Calculating the size of a directory in Python can be a useful task for managing storage space or analyzing data. Let's explore how to efficiently calculate this size.
Sum File Sizes Using os.walk
One approach involves traversing the directory and its subdirectories, summing the file sizes. This can be implemented using the os.walk function:
<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>
This function recursively computes the directory size, providing the total size in bytes.
One-liner Using os.listdir
For a quick calculation of the directory size without considering subdirectories, you can use a one-liner:
<code class="python">import os sum(os.path.getsize(f) for f in os.listdir('.') if os.path.isfile(f))</code>
This expression employs os.listdir to list all files in the current directory, and os.path.getsize to determine their sizes.
Using os.stat and os.scandir
Alternatively, you can use os.stat or os.scandir for calculating file sizes. os.stat provides additional file information, including size:
<code class="python">import os nbytes = sum(d.stat().st_size for d in os.scandir('.') if d.is_file())</code>
os.scandir offers improved performance in Python 3.5 and offers a more efficient way to iterate through directories.
Pathlib Solution
If you're using Python 3.4 , the pathlib library offers a convenient way to handle directory operations:
<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>
This pathlib solution combines the previous approaches for a concise and efficient calculation.
The above is the detailed content of How to Calculate Directory Size in Python?. For more information, please follow other related articles on the PHP Chinese website!