I'd like to know what's the fastest way to get a folder/directory size (in bytes as I'll format them to another size later) in python on a Windows OS pc. The current python version I am using is 3.8. I have tried the following function in python to obtain it:
def get_dir_size(directory):
total = 0
try:
for entry in os.scandir(directory):
if entry.is_file():
total += os.path.getsize(entry.path)
elif entry.is_dir():
total += get_directory_size(entry.path)
except NotADirectoryError:
return os.path.getsize(directory)
return total
However, I realised that the above code takes too long to run as I have quite a few folders to calculate its size, and a large folder with many degrees of subfolders will take up a lot of time to calculate the overall size.
Instead, I was attempting various approaches and have hit a roadblock for this current one. In this approach, I tried to use subprocess.run to run a powershell command and obtain the size. Here is the code I wrote to do so:
folder_path = C:\Users\username\Downloads\test_folder # Suppose this path is a legitimate path
command = fr"Get-ChildItem -Path {folder_path} -Recurse -ErrorAction SilentlyContinue | Measure-Object -Property Length -Sum | Select-Object Sum, Count"
proc = subprocess.run(command, shell=True, stdout=subprocess.PIPE)
print(proc.stdout)
The final output I get when I print proc.stdout
is empty, and an error is printed saying that the command I gave is not recognized as an internal or external command, operable program or batch file
.
I would appreciate it if I can get some advice on how to make this work, or if possible, provide suggestions on how to get the folder size in a shorter time possible. The current workable approach I have takes too many hours, and in between the network might get cut.
Thank you.