How to Get the Size of Directories in Python

文章推薦指數: 80 %
投票人數:10人

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



請為這篇文章評分?