I am doing backups in python script but i need to get the size of tar.gz file created in MB
How can i get the size in MB of that file
In order to extract or un-compress “. tar. gz” files using python, we have to use the tarfile module in python. This module can read and write .
The python os module has stat() function where we can pass the file name as argument. This function returns a tuple structure that contains the file information. We can then get its st_size property to get the file size in bytes.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With