代码之家  ›  专栏  ›  技术社区  ›  Igor Serebryany

python中的稀疏文件使用

  •  9
  • Igor Serebryany  · 技术社区  · 16 年前

    我在python中创建稀疏文件,如下所示:

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

    文件完成后,占用0磁盘空间,但其inode大小设置为截断值(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
    

    如何在python中获得文件的实际空间使用(分配的大小)?这个 stat 调用返回文件的外观大小,除了读取整个文件(可能会变得很大),我不知道如何获得真正的用法。

    >>> os.stat('testfile').st_size
    1024000
    
    1 回复  |  直到 8 年前
        1
  •  11
  •   wump    16 年前
    >>> os.stat('testfile').st_blocks*512
    0
    

    TADAA:)

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