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?
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?
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)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)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.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