-2

I'm trying to find a way to get the size of a folder that is not the folder my main code is being executed from.

I've tried looking for solutions on StackOverflow and GeeksForGeeks but with no luck.

Does anyone here know how to do this?

Musinks
  • 1
  • 1
  • What's wrong with the answers to https://stackoverflow.com/questions/1392413/calculating-a-directorys-size-using-python, for example? – MattDMo Apr 13 '22 at 00:11
  • What exactly do you mean by the "size" of a folder? – John Gordon Apr 13 '22 at 00:14
  • 1
    Does this answer your question? [Calculating a directory's size using Python?](https://stackoverflow.com/questions/1392413/calculating-a-directorys-size-using-python) – Alex Kosh Apr 13 '22 at 01:02
  • @MattDMo Those answers calculate the size of the directory the file you are executing is located in. I'm trying to find the sizes of directories that are not the place where my file is being executed. – Musinks Apr 13 '22 at 13:57
  • Then change the input directory. – MattDMo Apr 13 '22 at 16:49

1 Answers1

0

You'll need to get familiar with the os module.

  • os.path and submodules will help you get the folder's path in a system-dependent format (i.e. back/forward slashes depending on OS)
    For example, os.path.expanduser('~/') will return your home directory.
  • os.scandir() - Now that you have the path (os.path object), you can send this in as an argument to scandir which will return an iterator of DirEntry (docs) items for each of the files/directories in this folder. os.scandir(mypath)
    So the simplest way to access each item is with a for loop: for item in os.scandir(mypath): ....
  • stat() - which can be used on a DirEntry object (your item from the for loop) to report various information as os.stat_result objects. One of which is st_size on Windows, an integer representing the number of bytes in your file. Not kilobytes or megabytes, just bytes.
    Since you cannot see the size of a folder, you'll need to go inside the directory and iterate over every file, and if there's directories in there, iterate over their files too.
    os.path.join() will be useful here.

So a short example would look like:

import os

homeDir = os.path.expanduser('~/') # Your home directory
searchDir = os.path.join(homeDir, 'Some Big Folder', 'My Folder to Search')
# Adding the search folder, stored in 'My Big Folder', stored in your home directory

def findTotalSize(myPath):
  localSize = 0

  for item in os.scandir(myPath):
    print(item.name)
    localSize += item.stat().st_size # Size in bytes, zero for folders
    if item.is_dir():
      subDir = os.path.join(myPath, item.name) # Get path to this folder
      localSize += findTotalSize(subDir)

  return localSize

totalSizeInBytes = findTotalSize(searchDir)
totalSizeInMegabytes = (totalSizeInBytes/1024/1024) # Base 2 numbers
zodiac508
  • 156
  • 8