How to Get the Size of Directories in Python
文章推薦指數: 80 %
Have you ever wondered how you can get folder size in bytes using Python? As you may already know, os.path.get_size() function only returns the correct size ...
PythonCode
Menu
Home
MachineLearning
EthicalHacking
GeneralPythonTutorials
WebScraping
ComputerVision
PythonStandardLibrary
ApplicationProgrammingInterfaces
Database
Finance
PacketManipulationUsingScapy
NaturalLanguageProcessing
Healthcare
WebProgramming
PDFFileHandling
PythonforMultimedia
PythonTopics
Resources
Tutorials
About
ContactUs
WritewithUs
AbdouRockikz
·
4minread
·Updated
apr2022
·PythonStandardLibrary
Disclosure:Thispostmaycontainaffiliatelinks,meaningwhenyouclickthelinksandmakeapurchase,wereceiveacommission.
HaveyoueverwonderedhowyoucangetfoldersizeinbytesusingPython?Asyoumayalreadyknow,os.path.get_size()functiononlyreturnsthecorrectsizeofproperfilesandnotfolders.Inthisquicktutorial,youwilllearnhowyoucanmakeasimplefunctiontocalculatethetotalsizeofadirectoryinPython.
Let'sgetstarted,openupanewPythonfile:
importos
Thebelowcorefunctioncalculatesthetotalsizeofadirectorygivenitsrelativeorabsolutepath:
defget_directory_size(directory):
"""Returnsthe`directory`sizeinbytes."""
total=0
try:
#print("[+]Gettingthesizeof",directory)
forentryinos.scandir(directory):
ifentry.is_file():
#ifit'safile,usestat()function
total+=entry.stat().st_size
elifentry.is_dir():
#ifit'sadirectory,recursivelycallthisfunction
total+=get_directory_size(entry.path)
exceptNotADirectoryError:
#if`directory`isn'tadirectory,getthefilesizethen
returnos.path.getsize(directory)
exceptPermissionError:
#ifforwhateverreasonwecan'topenthefolder,return0
return0
returntotal
NoticethatIusedtheos.scandir()functionwhichreturnsaniteratorofentries(filesordirectories)inthedirectorygiven.
os.scandir()raisesNotADirectoryErrorifthegivenpathisn'tafolder(afileorlink),that'swhywecaughtthatexceptionandwereturnonlytheactualsizeofthatfile.
ItalsoraisesPermissionErrorifitcannotopenthefile(suchassystemfiles),inthatcase,we'lljustreturn0.
Theabovefunctionwillreturnthesizeinbytes,whichwillbeofcourse,unreadableforlargedirectories,asaresult,let'smakeafunctiontoscalethesebytestoKilo,Mega,Giga,etc:
defget_size_format(b,factor=1024,suffix="B"):
"""
Scalebytestoitsproperbyteformat
e.g:
1253656=>'1.20MB'
1253656678=>'1.17GB'
"""
forunitin["","K","M","G","T","P","E","Z"]:
ifb
延伸文章資訊
- 1Get the size of a file and directory in Python
- 2How to Get the Size of Directories in Python
Have you ever wondered how you can get folder size in bytes using Python? As you may already know...
- 3Get file size in python in 3 ways - codippa
- 4Get the size of a file and directory in Python
Get the size of a directory with os.scandir() (Python 3.5 or later) ... Use os.scandir() to get t...
- 5How to Check File and Folder Size in Python? - Geekflare
In this article, you'll learn to check the size of a file or folder in Python Python is one of th...