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 if it is symbolic link if not os.path.islink(fp): total_size += os.path.getsize(fp) return total_size print(get_size(), 'bytes')
Here is what the above code is Doing:
1. We define a function get_size() that takes a single argument, start_path.
2. We initialize total_size to 0.
3. We use os.walk() to walk through all the directories and subdirectories in start_path.
4. We use os.path.join() to join the directory path and the filename.
5. We use os.path.islink() to check if the file is a symbolic link.
6. We use os.path.getsize() to get the size of the file.
7. We add the size of the file to total_size.
8. We return the total_size.
9. We call the function get_size() and pass the path of the directory as the argument.
10. We print the size of the directory.