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
  • 31,788
  • 11
  • 91
  • 89
Mahakaal
  • 2,075
  • 9
  • 27
  • 38

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
  • 446,582
  • 72
  • 411
  • 327
6

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 < pow(1024,2):
            return f"{round(size/1024, 2)} KB"
        elif size < pow(1024,3):
            return f"{round(size/(pow(1024,2)), 2)} MB"
        elif size < pow(1024,4):
            return f"{round(size/(pow(1024,3)), 2)} GB"
>>> get_size("k.tar.gz")
1.4MB
jak bin
  • 380
  • 4
  • 8
  • Elegant codes <3 – Kaizendae May 25 '22 at 12:01
  • Nice piece of code. Under Linux (Ubuntu 22.04) to find the same value that is shown in file explorer you have to use `1000` instead of `1024` because Linux in that case shows kb, Mb, or Gb as explained https://ux.stackexchange.com/q/13815 – Cara Duf Jan 07 '23 at 06:50
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
  • 42,110
  • 11
  • 57
  • 76
  • (+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
0

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

chl
  • 27,771
  • 5
  • 51
  • 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
  • 369
  • 1
  • 4
  • 21