【问题标题】:How can I check file size in Python?如何在 Python 中检查文件大小?
【发布时间】:2011-01-07 10:13:36
【问题描述】:

我正在 Windows 中编写 Python 脚本。我想根据文件大小做一些事情。例如,如果大小大于0,我会发邮件给某人,否则继续其他事情。

如何查看文件大小?

【问题讨论】:

  • Path('./doc.txt').stat().st_size
  • 感谢@Boris 提供现代 Python (v3.4+) 答案:)
  • 请熟悉一个稀疏文件的现象

标签: python file


【解决方案1】:

使用os.path.getsize

>>> import os
>>> b = os.path.getsize("/path/isa_005.mp3")
>>> b
2071611

输出以字节为单位。

【讨论】:

  • 注意:os.path.getsize的实现就是return os.stat(filename).st_size
  • 那么使用 os.path.getsize 而不是 os.stat(file).st_size 会不会有一点性能损失?
  • @wordsforthewise 测量它!在我的电脑中约为 150 ns。
  • @wordsforthewise 如果您还想获取有关文件的其他信息(例如修改时间、文件类型),这将是一个更大的问题——那么您不妨从一个单一的通过os.stat 进行系统调用。然后差异可能会达到相当多的微秒:-)
  • 然后除以 1e+6 得到文件大小,单位为 MB,例如:output/1e+6
【解决方案2】:

您需要the object returned by os.statst_size 属性。您可以使用pathlib (Python 3.4+) 获得它:

>>> from pathlib import Path
>>> Path('somefile.txt').stat()
os.stat_result(st_mode=33188, st_ino=6419862, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=1564, st_atime=1584299303, st_mtime=1584299400, st_ctime=1584299400)
>>> Path('somefile.txt').stat().st_size
1564

或使用os.stat:

>>> import os
>>> os.stat('somefile.txt')
os.stat_result(st_mode=33188, st_ino=6419862, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=1564, st_atime=1584299303, st_mtime=1584299400, st_ctime=1584299400)
>>> os.stat('somefile.txt').st_size
1564

输出以字节为单位。

【讨论】:

  • 如果有的话,该值可以作为文件系统块大小的倍数(例如 4096 字节)传递。很高兴,它改为以字节形式给出。
  • @josch - 是的,这很好,对于“磁盘大小”,您可以将 stat_result.st_blocks 乘以块大小,但我仍在寻找如何以编程方式和跨平台获取它(不是通过tune2fs 等)
【解决方案3】:

其他答案适用于真实文件,但如果您需要适用于“类文件对象”的东西,试试这个:

# f is a file-like object. 
f.seek(0, os.SEEK_END)
size = f.tell()

在我有限的测试中,它适用于真实文件和 StringIO。 (Python 2.7.3。)当然,“类文件对象”API 并不是一个严格的接口,但API documentation 建议类文件对象应该支持seek()tell()

编辑

这和os.stat() 之间的另一个区别是即使您没有读取文件的权限,您也可以stat() 一个文件。显然,除非您具有读取权限,否则 seek/tell 方法将不起作用。

编辑 2

根据 Jonathon 的建议,这是一个偏执的版本。 (上面的版本将文件指针留在文件末尾,所以如果你试图从文件中读取,你会得到零字节!)

# f is a file-like object. 
old_file_position = f.tell()
f.seek(0, os.SEEK_END)
size = f.tell()
f.seek(old_file_position, os.SEEK_SET)

【讨论】:

  • 你不需要导入os,而是写f.seek(0, 2)从末尾开始寻找0字节。
  • 最后一行,如果没有使用osf.seek(old_file_position, 0)
  • 如果你使用整数文字而不是命名变量,你就是在折磨任何必须维护你的代码的人。没有令人信服的理由不导入 os
  • 感谢您的解决方案,我已经实施并且工作正常。只是为了确认,size 输出是以字节为单位的?
  • 显然这至少有点冒险,取决于Python如何实现#seek():wiki.sei.cmu.edu/confluence/display/c/…
【解决方案4】:
import os


def convert_bytes(num):
    """
    this function will convert bytes to MB.... GB... etc
    """
    for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
        if num < 1024.0:
            return "%3.1f %s" % (num, x)
        num /= 1024.0


def file_size(file_path):
    """
    this function will return the file size
    """
    if os.path.isfile(file_path):
        file_info = os.stat(file_path)
        return convert_bytes(file_info.st_size)


# Lets check the file size of MS Paint exe 
# or you can use any file path
file_path = r"C:\Windows\System32\mspaint.exe"
print file_size(file_path)

结果:

6.1 MB

【讨论】:

  • this function will convert bytes to MB.... GB... etc 错误。此函数会将字节转换为 MiB、GiB 等。请参阅 this post
  • 第 10 行可以在 Python >= 3.5 中更改为 return f'{num:.1f} {x}'
  • 感谢Matt M.,稍作更新,第10行可以在Python >= 3.5中改为return f'{num}{unit}' if unit == 'bytes' else f'{num:.1f}{unit}'
【解决方案5】:

使用pathlibadded in Python 3.4PyPI 上可用的反向端口):

from pathlib import Path
file = Path() / 'doc.txt'  # or Path('./doc.txt')
size = file.stat().st_size

这实际上只是一个围绕os.stat 的接口,但使用pathlib 提供了一种访问其他文件相关操作的简便方法。

【讨论】:

    【解决方案6】:

    如果我想从bytes 转换为任何其他单位,我会使用bitshift 技巧。如果您通过10 进行右移,则基本上将其按一个顺序(多个)移动。

    示例:5GB are 5368709120 bytes

    print (5368709120 >> 10)  # 5242880 kilobytes (kB)
    print (5368709120 >> 20 ) # 5120 megabytes (MB)
    print (5368709120 >> 30 ) # 5 gigabytes (GB)
    

    【讨论】:

    • 这不能回答问题。问题在于查找文件的大小,而不是格式化结果以供人类使用。
    • 这些数字是错误的,因此令人困惑。 5GB 是 5e9 字节。这应该是某种人类可读的近似值吗?你甚至会在哪里使用这样的东西?
    • 1-bit=>2 ... 2-bits=>4 ... 3-bits=>8 ... 4-bits=>16 ... 5-bits=>32 ... 6 位=>64 ... 7 位=>128 ... 8 位=>256 ... 9 位=>512 ... 10 位=>1024 ... 1024 字节是 1kB ... => 20 位 => 1024 * 1024 = 1,048,576 字节,即 1024kB,而 1MB ... => 30 位 => 1024 * 1024 * 1024 = 1,073,741,824 字节,即 1,048,576 kB,以及1024MB 和 1GB……您将科学记数法和小数位与计算中使用的二进制/base-2 表示混淆了。 5x9 = 5 x 10^9 = 5,000,000,000
    • 伙计们,他没有混淆任何东西......他只是给出了一个近似值,当他说“基本上”时很明显。 2^10 约为。 10^3。事实上,这种近似非常普遍,以至于it has a name: MebiGibiTebi 分别是 Mega、Giga 和 Tera。关于不回答问题,@WillManley,你有一个公平的观点! ;-p
    • @WillManley 它没有回答这个问题,但它给了 OP 更多的学习 可能回答这个问题的人可以编辑这个问题和这个技巧。谢谢你..我需要这个
    【解决方案7】:

    严格来说,Python代码(+伪代码)将是:

    import os
    file_path = r"<path to your file>"
    if os.stat(file_path).st_size > 0:
        <send an email to somebody>
    else:
        <continue to other things>
    

    【讨论】:

      【解决方案8】:

      我们有两个选项都包括导入 os 模块

      1)

      import os
      os.stat("/path/to/file").st_size
      

      os.stat() 函数返回一个对象,该对象包含许多标题,包括文件创建时间和上次修改时间等。其中st_size 给出了文件的确切大小。 文件路径可以是绝对路径也可以是相对路径。

      2) 在这里,我们必须提供准确的文件路径,文件路径可以是相对的,也可以是绝对的。

      import os
      os.path.getsize("path of file")
      

      【讨论】:

      • os.path.getsize 使用相对路径
      【解决方案9】:

      您可以使用os 模块中的stat() 方法。您可以为它提供字符串、字节甚至 PathLike 对象形式的路径。它也适用于文件描述符。

      import os
      
      res = os.stat(filename)
      
      res.st_size # this variable contains the size of the file in bytes
      

      【讨论】:

        【解决方案10】:
        #Get file size , print it , process it...
        #Os.stat will provide the file size in (.st_size) property. 
        #The file size will be shown in bytes.
        
        import os
        
        fsize=os.stat('filepath')
        print('size:' + fsize.st_size.__str__())
        
        #check if the file size is less than 10 MB
        
        if fsize.st_size < 10000000:
            process it ....
        

        【讨论】:

          【解决方案11】:

          您可以使用检查文件大小

          import sys
          print(sys.getsizeof(your_file))
          

          例如,

          nums = range(10000)
          squares = [i**2 for i in nums]
          print(sys.getsizeof(squares))
          

          【讨论】:

          • 这给出了内存对象的大小,而不是文件系统中文件的大小
          猜你喜欢
          • 2018-04-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-08-15
          • 2022-01-12
          • 2011-12-16
          相关资源
          最近更新 更多