我正在尝试获取另一个进程仍在下载的文件的大小。我使用了下面的代码(我在 here 中找到的):
os.stat(filepath).st_blocks*512
但是,它也返回文件的分配大小。在最近的检查中,我发现这个解决方案的准确性取决于它所使用的操作系统。目前,我的操作系统是带有 ext3 文件系统的 ubuntu 12.04 服务器。有没有另一种方法可以在 python 中查找真实文件大小?
请您参考如下方法:
On some Unix systems (such as Linux), the following attributes may also be available:
- st_blocks - number of 512-byte blocks allocated for file
- st_blksize - filesystem blocksize
- st_rdev - type of device if an inode device
- st_flags - user defined flags for file
您似乎想要的是 st_blocks * st_blksize。请注意,这不是文件的实际大小,它是st_size 成员。 block 数乘以 block 大小将大于实际文件大小。
注意: 当它说“st_blocks - 为文件分配的 512 字节 block 数”时,数字 512 实际上是依赖于系统的。 The POSIX specification说
The unit for the st_blocks member of the stat structure is not defined within POSIX.1-2008. In some implementations it is 512 bytes. It may differ on a file system basis.
如果 st_block 属性可用,那么如果它是其他值也不要感到惊讶。
