- 1 year ago
What is the fastest way to get a folder size in python on Windows pc
Comment
1 / 1
To get the folder size in Python on a Windows PC, one of the fastest ways is to use the os.walk()
function to iterate over all files and folders within the target folder and calculate their sizes. Here's an example implementation:
pythonimport os
def get_folder_size(folder_path):
total_size = 0
for root, dirs, files in os.walk(folder_path):
for file in files:
file_path = os.path.join(root, file)
total_size += os.path.getsize(file_path)
return total_size
# Usage example
folder_path = r'C:\path\to\folder'
size_bytes = get_folder_size(folder_path)
size_kb = size_bytes / 1024
size_mb = size_bytes / (1024 * 1024)
size_gb = size_bytes / (1024 * 1024 * 1024)
print(f"Folder size: {size_bytes} bytes / {size_kb:.2f} KB / {size_mb:.2f} MB / {size_gb:.2f} GB")
In this example, the get_folder_size()
function takes a folder path as input and uses os.walk()
to traverse all files and folders within the target folder. It uses os.path.getsize()
to get the size of each file and adds it to the total_size
variable.
The size is returned in bytes, and you can convert it to kilobytes, megabytes, or gigabytes as shown in the example.
Please note that calculating the size of a large folder can take some time, depending on the number and size of files.