How to calculate the total size of a directory in Python
How to calculate the total size of a directory in Python.
Here's a step-by-step tutorial on how to calculate the total size of a directory in Python.
- Import the necessary modules:
import os
- Define a function to calculate the size of a file or directory:
def get_size(path):
total_size = 0
# If the path is a file, return its size
if os.path.isfile(path):
return os.path.getsize(path)
# If the path is a directory, iterate over its contents
for dirpath, dirnames, filenames in os.walk(path):
# Calculate the total size of all files in the directory
for f in filenames:
fp = os.path.join(dirpath, f)
total_size += os.path.getsize(fp)
return total_size
- Prompt the user to enter the directory path:
directory = input("Enter the directory path: ")
- Call the
get_size()function with the directory path and print the result:
size = get_size(directory)
print("Total size:", size, "bytes")
That's it! When you run the program, it will prompt you to enter the directory path. Once you provide the path, it will calculate the total size of the directory and display it in bytes.
Here's a complete example:
import os
def get_size(path):
total_size = 0
if os.path.isfile(path):
return os.path.getsize(path)
for dirpath, dirnames, filenames in os.walk(path):
for f in filenames:
fp = os.path.join(dirpath, f)
total_size += os.path.getsize(fp)
return total_size
directory = input("Enter the directory path: ")
size = get_size(directory)
print("Total size:", size, "bytes")
Feel free to modify the code as needed for your specific use case.