获取稀疏文件真实大小

转至 http://stackoverflow.com/questions/3211999/sparse-file-usage-in-python


问题

5 down vote favorite

Please login or register to vote for this post.

(click on this box to dismiss)

I'm creating sparse files in python as follows:

>>> f = open('testfile', 'ab')
>>> f.truncate(1024000)
>>> f.close()

when the file is done, it takes up 0 disk space, but its inode size is set to my truncated value (1000K):

igor47@piglet:~/test$ ls -lh testfile 
-rw-r--r-- 1 igor47 igor47 1000K 2010-07-09 04:02 testfile
igor47@piglet:~/test$ du -hs testfile 
0   testfile

how do i get the file's real space usage inside python? the stat call returns the file's apparent size, and i have no idea how else to get the real usage other than to read the entire file (it may become quite large)

>>> os.stat('testfile').st_size
1024000

答案


up vote 6 down vote accepted
>>> os.stat('testfile').st_blocks*512
0

Tadaa :)

st_blocks is the number of 512-byte blocks actually allocated to the file. Note thatst_blocks is not guaranteed to be present in all operating systems, but those that support sparse files generally do.

share | improve this answer
 
2 
st_blksize provides actual block size of the filesystem. Generally speaking it doesn't have to be 512 bytes. –  SilentGhost Jul 9 '10 at 11:33
1 
I was confused for a moment, but that's not true.st_blksize is the "preferred" file system block size. st_blocks is guaranteed to be in blocks of 512 bytes (see the manpage). –  wump Jul 9 '10 at 12:49
 
This particular solution was working this morning, but after i've changed the server machine it suddenly stopped working. Do you have any advice on that? –  Hgeg Oct 8 at 0:42


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值