How to calculate a directory size using Python? - Tutorialspoint
文章推薦指數: 80 %
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
延伸文章資訊
- 1Get the size of a folder in Python - CodeSpeedy
How to get the size of a folder in Python? · os.path.join() method joins different path component...
- 2Get the size of a file and directory in Python
- 3Calculating a directory's size using Python? - Stack Overflow
This walks all sub-directories; summing file sizes: ... Python 3.5 recursive folder size using os...
- 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 calculate a directory size using Python? - Tutorialspoint
To get the size of a directory, you'll have to walk the whole directory tree and add size of each...