To find the size of a directory in Python, we can use the os
module. The basic idea is to recursively iterate over all the files and directories within the given directory and sum up the sizes of all the files. Here's a function that does that:
main.py374 chars13 lines
This function takes a single argument dir_path
, which is the path to the directory that we want to find the size of. We start by initializing a variable total
to 0. We then use the os.scandir()
function to iterate over all the entries in the directory. For each entry, we check if it's a file or a directory. If it's a file, we use the st_size
attribute of its stat()
object to get its size and add it to the total
. If it's a directory, we recursively call get_dir_size()
with its path and add the result to the total
. Finally, we return the total
size.
Here's an example of using this function:
main.py109 chars4 lines
gistlibby LogSnag