Os.path.getsize Returns an invalid value?

def size_of_dir(dirname): print("Size of directory: ") print(os.path.getsize(dirname)) 

is a code. dirname is a directory with 130 files in size 1kb . When I call this function, it returns 4624 , which is NOT the size of the directory ... why is this?

+6
source share
2 answers

This value (4624B) represents the size of the file that this directory describes. Directories are described as inodes ( http://en.wikipedia.org/wiki/Inode ), which contain information about the files and directories that it contains.

To get the number of files / subdirectories inside this path, use:

 len(os.path.listdir(dirname)) 

To get the total amount of data, you can use the code in this matter , that is (as posted @linker)

  sum([os.path.getsize(f) for f in os.listdir('.') if os.path.isfile(f)]). 
+10
source

Using os.path.getsize() will only result in the size of the directory, NOT its contents. Therefore, if you call getsize() in any directory, you will always be the same size, since they are all represented the same way. Otherwise, if you call it in a file, it will return the actual file size.

If you need content that you will need to do recursively, for example below:

 sum([os.path.getsize(f) for f in os.listdir('.') if os.path.isfile(f)]) 
+5
source

Source: https://habr.com/ru/post/914675/


All Articles