13

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

plaes
  • 30,266
  • 10
  • 85
  • 86
Mahakaal
  • 1,973
  • 9
  • 26
  • 36

5 Answers5

40

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.

Community
  • 1
  • 1
Mark Longair
  • 415,589
  • 70
  • 403
  • 320
2

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

Keith
  • 40,128
  • 10
  • 53
  • 74
  • (+1) Seems much better than my idea (I initially thought the OP wants to assess what's in the tar file too). – chl May 21 '11 at 08:23
1

To get file size in MB, I created this function:

import os

def get_size(path):
    size = os.path.getsize(path)
    if size < 1024:
        return f"{size} bytes"
    elif size < 1024*1024:
        return f"{round(size/1024, 2)} KB"
    elif size < 1024*1024*1024:
        return f"{round(size/(1024*1024), 2)} MB"
    elif size < 1024*1024*1024*1024:
        return f"{round(size/(1024*1024*1024), 2)} GB"
>>> get_size("k.tar.gz")
1.4MB
Flair
  • 2,123
  • 1
  • 24
  • 39
jak bin
  • 71
  • 1
  • 3
0

According to Python on-line docs, you should look at the size attributes of a TarInfo object.

chl
  • 25,925
  • 5
  • 49
  • 71
  • @Mahakaal It works with `*.tar` file too (just read it with the `r` flag and not `r:gz` passed to `tarfile.open`). However, it gives the size of each element included in the tar file (easy to sum up, though), so maybe one of the alternative answer might better suit your needs. – chl May 21 '11 at 08:21
0

You can use the below command to get it directly without any hazel

os.path.getsize('filename.tar') >> 20
print str(filename.tgz) + " MB"
manjesh23
  • 347
  • 1
  • 3
  • 19