Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to get the size of a folder and all the files inside from python?

Tags:

python

If there will be a small number of files it should be easy with a recursive function to pass through all the files and add the size but what if there are lots of files, and by lots i really mean lots of files.

like image 303
daniels Avatar asked Dec 02 '08 19:12

daniels


People also ask

How do I get the total size of a folder?

How to view the file size of a directory. To view the file size of a directory pass the -s option to the du command followed by the folder. This will print a grand total size for the folder to standard output.

How the check the size of all files from a directory?

Right-click the file and click Properties. The image below shows that you can determine the size of the file or files you have highlighted from in the file properties window. In this example, the chrome. jpg file is 18.5 KB (19,032 bytes), and that the size on disk is 20.0 KB (20,480 bytes).

Which view helps us to show the size of a folder?

You can view folder size in Windows using one of below options. In File explorer, right click on folder for which you want to see folder size, and click on "Properties" in context menu. This will display folder properties dialog showing folder size in "Size" and "Size on disk" display field.

How do I check the size of a file in python?

Use os.path.getsize() function getsize('file_path') function to check the file size. Pass the file name or file path to this function as an argument.


2 Answers

You mean something like this?

import os
for path, dirs, files in os.walk( root ):
    for f in files:
        print path, f, os.path.getsize( os.path.join( path, f ) )
like image 191
S.Lott Avatar answered Nov 14 '22 23:11

S.Lott


There is no other way to compute the size than recursively invoking stat. This is independent of Python; the operating system just provides no other way.

The algorithm doesn't have to be recursive; you can use os.walk.

There might be two exceptions to make it more efficient:

  1. If all the files you want to measure fill a partition, and the partition has no other files, then you can look at the disk usage of the partition.
  2. If you can continuously monitor all files, or are responsible for creating all the files yourself, you can generate an incremental disk usage.
like image 37
Martin v. Löwis Avatar answered Nov 14 '22 23:11

Martin v. Löwis