如何在python中检查文件大小?

我在Windows中编写Python脚本。 我想根据文件大小做一些事情。 例如,如果大小大于0,我将向某人发送电子邮件,否则继续其他操作。

如何检查文件大小?


#1楼

其他答案适用于实际文件,但是如果您需要适用于“类文件的对象”的文件,请尝试以下操作:

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

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

编辑

此文件与os.stat()之间的另一个区别是,即使您没有读取文件的权限,也可以对文件进行stat() 。 显然,除非您具有阅读许可,否则搜索/讲述方法将无法工作。

编辑2

在乔纳森的建议下,这是一个偏执的版本。 (以上版本将文件指针留在文件的末尾,因此,如果您尝试从文件中读取文件,则将返回零字节!)

# 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)

#2楼

使用os.path.getsize

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

输出以字节为单位。


#3楼

使用os.stat ,并使用结果对象的st_size成员:

>>> import os
>>> statinfo = os.stat('somefile.txt')
>>> statinfo
(33188, 422511L, 769L, 1, 1032, 100, 926L, 1105022698,1105022732, 1105022732)
>>> statinfo.st_size
926L

输出以字节为单位。


#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

#5楼

使用pathlib在Python 3.4中添加或在PyPI上可用的pathlib ):

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

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


#6楼

严格遵循这个问题,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>

#7楼

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

示例: 5GB are 5368709120 bytes

print (5368709120 >> 10)  # 5242880 kilo Bytes (kB)
print (5368709120 >> 20 ) # 5120 Mega Bytes(MB)
print (5368709120 >> 30 ) # 5 Giga Bytes(GB)

#8楼

#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 ....
  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值