12

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 (allocated size) 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
4

1 回答 1

17
>>> os.stat('testfile').st_blocks*512
0

多达 :)

st_blocks是实际分配给文件的 512 字节块的数量。请注意,st_blocks不能保证在所有操作系统中都存在,但支持稀疏文件的操作系统通常会存在。

于 2010-07-09T11:20:05.997 回答