How to calculate a directory size using Python? - Tutorialspoint

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

To get the size of a directory, you'll have to walk the whole directory tree and add size of each file. To do this you can use the os.walk() ... TrendingCategories DataStructure Networking RDBMS OperatingSystem Java iOS HTML CSS Android Python CProgramming C++ C# MongoDB MySQL Javascript PHP SelectedReading UPSCIASExamsNotes Developer'sBestPractices QuestionsandAnswers EffectiveResumeWriting HRInterviewQuestions ComputerGlossary WhoisWho HowtocalculateadirectorysizeusingPython? PythonServerSideProgrammingProgramming Togetthesizeofadirectory,you'llhavetowalkthewholedirectorytreeandaddsizeofeachfile.Todothisyoucanusetheos.walk()andos.path.getsize()functions.Forexampleimportos total_size=0 start_path='.' #Togetsizeofcurrentdirectory forpath,dirs,filesinos.walk(start_path):   forfinfiles:     fp=os.path.join(path,f)     total_size+=os.path.getsize(fp) print("Directorysize:"+str(total_size))Ifyou'reon*NIXOSesthenyoucouldsimplycalltheducommandusingsubprocessmoduleasitismucheasierthanthewayabove.Forexample,importsubprocess path='.' size=subprocess.check_output(['du','-sh',path]).split()[0].decode('utf-8') print("Directorysize:"+size)OutputRunningeitherprogramwillgivetheoutput:Directorysize:1524664 RajendraDharmkar Publishedon27-Dec-201707:26:02 RelatedQuestions&AnswersHowtocreateadirectoryusingPython? HowtoremoveadirectoryusingPython? HowtocalculatethesizeoffolderusingJava? HowtocalculatetheSizeofFolderusingC#? HowtocreateadirectoryrecursivelyusingPython? HowtoremoveadirectoryrecursivelyusingPython? HowtorenamedirectoryusingPython? HowtocreateauniquedirectorynameusingPython? HowtochangecurrentdirectoryusingPython? HowtocopyfilestoanewdirectoryusingPython? HowtocheckthepermissionsofadirectoryusingPython? HowtochangethepermissionofadirectoryusingPython? HowtochangetheownerofadirectoryusingPython? HowtocreateaziparchiveofadirectoryusingPython? HowtocreateadirectoryusingJava? PreviousPage PrintPage NextPage  Advertisements Print  AddNotes  Bookmarkthispage  ReportError  Suggestions Save Close Dashboard Logout



請為這篇文章評分?