Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 738
Mahakaal Avatar asked May 21 '11 08:05

Mahakaal


People also ask

How do I read a tar GZ file in Python?

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 .

How do I get the size of a file in Python?

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.


2 Answers

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.

like image 73
Mark Longair Avatar answered Sep 20 '22 19:09

Mark Longair


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

like image 24
Keith Avatar answered Sep 19 '22 19:09

Keith