开发者

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

I am doing 开发者_如何学Pythonbackups 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


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.


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


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


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


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

os.path.getsize('filename.tar') >> 20
print str(filename.tgz) + " MB"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜