How to get the size of tar.gz in (MB) file in python

It's not clear from your question whether you want to the compressed or uncompressed size of the file, but in the former case, it's easy with the os.path.getsize function from the os module

>>> import os
>>> os.path.getsize('flickrapi-1.2.tar.gz')
35382L

To get the answer in megabytes you can shift the answer right by 20, e.g.

os.path.getsize('large.tar.gz') >> 20

Although that operation will be done in integers - if you want to preserve fractions of a megabyte, divide by (1024*1024.0) instead. (Note the .0 so that the divisor will be a float.)

Update: In the comments below, Johnsyweb points out a useful recipe for more generally producing human readable representations of file sizes.


Use the os.stat() function to get a stat structure. The st_size attribute of that is the size of the file in bytes.