Get the size of a folder in Python - CodeSpeedy

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

How to get the size of a folder in Python? · os.path.join() method joins different path components such as directories, sub directories, files, etc. Each ... HowtogetthesizeofafolderinPython?ByAsmaKhanInthistutorial,wewilllearnhowtogetthesizeofafolderinPython.Letusfirstseesomeprerequisiterequiredforthiscode.TheOSmoduleinPythonenablesustointeractwiththeoperatingsystemandperformvariousrelatedtasks.ThismoduleisapredefinedstandardmoduleofPython.os.pathmoduleisasubmoduleoftheOSmodule.Itcontainsvariousfunctionsonpathnamesorinsimplerterms,usedinsteadoflongfilenames.Toaccessthismodule,weusethesyntax:importosSomefunctionsofos.pathwewillneedtosolvethisproblemare:os.path.join()methodjoinsdifferentpathcomponentssuchasdirectories,subdirectories,files,etc.Eachcomponentisseparatedby(\).Syntax:os.path.join(path)os.path.getsize()methodreturnsthesizeofthefileordirectoryinbytes.Syntax:os.path.getsize(path)Anothermethodthatwillbeusedisos.walk().Itwalksthetreeofdirectorieseithertop-downorbottom-upandgeneratesthefilenames.3tuplesareyielded:dirpath,dirnames,filenames.PythonprogramtogeneratesizeofafolderProblemstatement: WriteaPythonprogramtogetthesizeofafolder.Steps/Algorithm: ImporttheOSmodule.Defineafunction(size)andgivethepathofthefolderordirectory.Initializethetotalsizeas0.Navigateorwalkthroughthedirectorytreeusingthe os.walk() method.Joinorconcatenateallthecomponentsofthepathusingthe os.path.join() function.Getthesizesofindividualfilesinthedirectoryandaddittothetotalsize.Printthetotalsizegenerated.Program/Code:importos defsize(path='C:\\Users\ADMIN\Documents\programs\Python'): #initializethesize total_size=0 #usethewalk()methodtonavigatethroughdirectorytree fordirpath,dirnames,filenamesinos.walk(path): foriinfilenames: #usejointoconcatenateallthecomponentsofpath f=os.path.join(dirpath,i) #usegetsizetogeneratesizeinbytesandaddittothetotalsize total_size+=os.path.getsize(f) returntotal_size print(size())IfwerunourprogramthenitwillshowthesizeofourgivenfileinthePythonprogram:1246Ihope,youhaveunderstoodhowwecangetthesizeofacompletefolderwithjustafewlinesofcode.Also,read:CountthenumberoffilesinadirectoryinPythonHowtogetthesizeofafileinPython LeaveaReplyCancelreplyYouremailaddresswillnotbepublished.Requiredfieldsaremarked*Comment*Name*Email*«FindthenextgreaternumberfromthesamesetofdigitsinC++StringPalindromeinJava»SearchLatestArticlesGlyphiconsinBootstrapRemoveduplicateelementsfromanarrayinSwiftEasyexampleofopenpyxliter_rowsinPythonHowtofindindexofmaximumandminimumelementinvectorinC++DictionariesinSwiftRelatedPostsHowtoremoveallemptyfileswithinafolderanditssubfoldersinPython?CountthenumberoffilesinadirectoryinPython.HowtogettheparentofthecurrentdirectoryinPython



請為這篇文章評分?