文件系统很少允许文件长度为任意数量的字节,而是更喜欢填充它们以适应一定数量的块。Python 的 os.path.getsize() 被记录为以字节为单位返回大小,但我不确定它是否被操作系统(在我的情况下是 linux)或文件系统四舍五入到块大小。对于我的应用程序,我必须知道能够从大文件 (~1GB) 中读取的确切字节数。对此有什么保证?
1 回答
2
Python 不做任何保证。该os.path.getsize()
函数返回 调用的st_size
字段os.stat()
。这是对stat
系统调用的直接调用。
所有文档都stat
简单地命名st_size
为文件大小,以字节为单位。
在我的 Debian 测试系统stat
上给出了真实的文件大小:
$ stat -fc %s . # fs block size
4096
$ head -c 2048 < /dev/urandom > 2kb
$ head -c 6168 < /dev/urandom > 6kb
$ head -c 12345 < /dev/urandom > 12andabitkb
$ ls --block-size=1 -s *kb # block use in bytes
16384 12andabitkb 4096 2kb 8192 6kb
$ ls --block-size=4K -s *kb # block count per file
4 12andabitkb 1 2kb 2 6kb
$ python3 -c 'import os, glob; print(*("{:<11} {}".format(f, os.path.getsize(f)) for f in glob.glob("*kb")), sep="\n")'
2kb 2048
12andabitkb 12345
6kb 6168
于 2018-06-13T16:24:39.197 回答