To implement the total size of files in a simple statistics folder with Python

Source: Internet
Author: User

Using Python to achieve the size of the statistics folder, you need to use the OS module. The OS module provides a way to count file sizes: os.path.getsize (Dirpath)

The specific code is as follows:

ret = Os.sep.join (__file__. Split ('/') [:-2]) name=os.path.basename (ret) sum=0deffunc (Dirpath): LST= Os.listdir (Dirpath)#a list of files under a large folder, including folders     forElinchLst:new_dir= dirpath+'\\'+ElifOs.path.isfile (new_dir): GetSize=os.path.getsize (New_dir)Globalsum sum+=GetSizeElse: Func (New_dir)returnSumnum=func (ret)Print('the size of the folder%s is%s bytes'% (Name,num))
total file size in the statistics folder

This statistic needs to use recursive thought, first obtains the folder path which needs the statistic size, obtains the folder all folders and the file, carries on the If judgment, if is the file, calculates the file size to add the sum, if is the folder, continues carries on the last step operation, the statistic internal file and the folder, Continue to judge. Until all of the traversal is complete, end the loop.

In this case, the last sum is the sum of all the files in the large folder.

To implement the total size of files in a simple statistics folder with Python

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.