Linux 如何在python中获取(MB)文件中tar.gz的大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6080477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 04:11:01  来源:igfitidea点击:

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

pythonlinuxfile-io

提问by Mahakaal

I am doing backups in python script but i need to get the size of tar.gz file created in MB

我正在用 python 脚本进行备份,但我需要获取以 MB 为单位创建的 tar.gz 文件的大小

How can i get the size in MB of that file

我如何获得该文件的大小(以 MB 为单位)

采纳答案by Mark Longair

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.getsizefunction from the os module

从您的问题中不清楚您是想要文件的压缩大小还是未压缩大小,但在前一种情况下,使用os 模块中os.path.getsize函数很容易

>>> 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.

要获得以兆字节为单位的答案,您可以将答案右移 20,例如

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 .0so that the divisor will be a float.)

尽管该操作将以整数完成 - 如果您想保留兆字节的分数,请(1024*1024.0)改为除以。(注意.0使除数成为浮点数。)

Update:In the comments below, Johnsywebpoints out a useful recipe for more generally producing human readable representations of file sizes.

更新:在下面的评论中,Johnsyweb指出了一个有用的方法,可以更普遍地生成人类可读的文件大小表示

回答by Keith

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

使用该os.stat()函数获取统计结构。它的st_size属性是以字节为单位的文件大小。

回答by chl

According to Python on-line docs, you should look at the sizeattributes of a TarInfoobject.

根据 Python在线文档,您应该查看对象的size属性TarInfo