【问题标题】:Does Python's os.path.getsize() have true byte resolution?Python 的 os.path.getsize() 是否具有真正的字节分辨率?
【发布时间】:2018-06-13 16:17:08
【问题描述】:

文件系统很少允许文件长度为任意字节数,而是更喜欢填充它们以适应一定数量的块。 Python 的 os.path.getsize() 被记录为以字节为单位返回大小,但我不确定它是否被操作系统(在我的情况下是 linux)或文件系统四舍五入到块大小。对于我的应用程序,我必须知道能够从大文件 (~1GB) 中读取的确切字节数。对此有什么保证?

【问题讨论】:

  • 这取决于您的文件系统。某些文件系统(如 procfs 和 sysfs)根本不会在统计数据中返回非零大小。如果你想要完全确定,打开文件,seek() 到最后,然后使用tell() 给你当前的偏移量。也就是说,对于用于常规(非生成、非虚拟、非套接字、非块设备)文件的常用文件系统上的常规文件,os.path.getsize() 将返回您要查找的内容。

标签: python filesize disk


【解决方案1】:

Python 不做任何保证。 os.path.getsize() 函数返回 st_size field of a os.stat() call。这是对stat system call 的直接调用。

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

【讨论】:

    猜你喜欢
    • 2011-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-27
    • 1970-01-01
    • 2022-07-23
    • 1970-01-01
    相关资源
    最近更新 更多