Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

os.path.getsize Returns Incorrect Value?

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

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

like image 368
Bobby Tables Avatar asked May 01 '12 21:05

Bobby Tables


People also ask

What does os path Getsize return?

path. getsize() method in Python is used to check the size of specified path. It returns the size of specified path in bytes. The method raise OSError if the file does not exist or is somehow inaccessible.

What is os path?

The os.path module is always the path module suitable for the operating system Python is running on, and therefore usable for local paths. However, you can also import and use the individual modules if you want to manipulate a path that is always in one of the different formats.

Is path exist Python?

exists() method in Python is used to check whether the specified path exists or not. This method can be also used to check whether the given path refers to an open file descriptor or not.


1 Answers

Using os.path.getsize() will only get you the size of the directory, NOT of its content. So if you call getsize() on any directory you will always get the same size since they are all represented the same way. On contrary, if you call it on a file, it will return the actual file size.

If you want the content you will need to do it recursively, like below:

sum([os.path.getsize(f) for f in os.listdir('.') if os.path.isfile(f)])
like image 70
Charles Menguy Avatar answered Sep 28 '22 07:09

Charles Menguy