Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中检查文件大小?_Python_File - Fatal编程技术网

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

如何在Python中检查文件大小?,python,file,Python,File,我正在Windows中编写Python脚本。我想根据文件大小做一些事情。例如,如果大小大于0,我将向某人发送电子邮件,否则继续执行其他操作 如何检查文件大小?使用: 输出以字节为单位。您需要的属性。您可以使用(Python 3.4+): 或使用: 输出以字节为单位。其他答案适用于真实文件,但如果您需要适用于“类似文件的对象”的内容,请尝试以下方法: # f is a file-like object. f.seek(0, os.SEEK_END) size = f.tell() 在我有限的测

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

如何检查文件大小?

使用:

输出以字节为单位。

您需要的属性。您可以使用(Python 3.4+):

或使用:


输出以字节为单位。

其他答案适用于真实文件,但如果您需要适用于“类似文件的对象”的内容,请尝试以下方法:

# f is a file-like object. 
f.seek(0, os.SEEK_END)
size = f.tell()
在我有限的测试中,它适用于真实文件和StringIO。(Python 2.7.3.)当然,“类似文件的对象”API并不是一个严格的接口,但建议类似文件的对象应该支持
seek()
tell()

编辑

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

编辑2

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


使用
pathlib
(或上提供的后端口):


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

严格地说,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>
导入操作系统
文件路径=r“”
如果os.stat(文件路径).st\u大小>0:
其他:

如果我想从
字节
转换到任何其他单位,我会使用
位移位
技巧。如果按
10
右移,则基本上是按顺序(倍数)右移

示例:
5GB为5368709120字节

#获取文件大小、打印、处理。。。
#Os.stat将在(.st_size)属性中提供文件大小。
#文件大小将以字节为单位显示。
导入操作系统
fsize=os.stat('filepath')
打印('size:'+fsize.st_size.\uuuu str_uuu())
#检查文件大小是否小于10 MB
如果fsize.st_size<10000000:
处理它。。。。

我们有两个选项,都包括导入操作系统模块

(一)

导入操作系统
os.stat(“/path/to/file”).st\u大小
as
os.stat()。。其中
st_size
给出了文件的确切大小。 文件路径可以是绝对路径,也可以是相对路径

(二) 在此,我们必须提供确切的文件路径,文件路径可以是相对的,也可以是绝对的

导入操作系统
getsize(“文件路径”)

您可以使用

import sys
print(sys.getsizeof(your_file))
比如说,

nums = range(10000)
squares = [i**2 for i in nums]
print(sys.getsizeof(squares))
您可以使用
os
模块中的
stat()
方法。您可以以字符串、字节甚至类似路径的对象的形式为其提供路径。它也适用于文件描述符

import os

res = os.stat(filename)

res.st_size # this variable contains the size of the file in bytes


注意:
os.path.getsize
的实现只是
返回os.stat(文件名).st_size
,因此使用os.path.getsize而不是os.stat(文件名).st_size?@words可以测量它~“我的电脑中有150 ns。@Words或者,如果您还想获取有关该文件的其他信息(例如修改时间、文件类型),那么这更是一个问题——那么您最好通过
os.stat
从一个系统调用中获取所有信息。然后差异可能会达到相当数量的微秒:-),然后除以1e+6以获得文件大小(MB),例如:输出/1e+6您不需要导入
os
,而是写入
f.seek(0,2)
以从末尾查找0字节。对于最后一行,如果未使用
os
,则:
f.seek(旧文件位置,0)
如果您使用整数文本而不是命名变量,那么您正在折磨任何必须维护代码的人。没有令人信服的理由不导入
操作系统
。感谢您提供的解决方案,我已经实现了,并且运行良好。请确认,
size
输出是以字节为单位的?显然,这至少有一点风险,这取决于Python实现
#seek()
的方式:如果有的话,该值可以作为文件系统块大小的倍数传递(例如4096字节)。很高兴,它是以字节的形式给出的。@josch-是的,这很好,因为“磁盘上的大小”可以乘以
stat\u结果。st\u块
乘以块大小,但我仍在研究如何通过编程和跨平台(而不是通过
tune2fs
等)获取它。
此函数将字节转换为MB。。。。GB。。。etc
错误。此函数将字节转换为MiB、GiB等。请参阅。在Python>=3.5中,第10行可以更改为
return f'{num:.1f}{x}'
。谢谢Matt M,稍加更新,第10行可以更改为
return f'{num}{unit}',如果unit='bytes',否则在Python>=3.5中,这并不能回答问题。问题在于找到文件的大小,而不是格式化结果以供人使用。这些数字是错误的,因此容易混淆。5GB是5e9字节。这应该是某种人类可读的近似值吗?你会在哪里使用这样的东西?1位=>2。。。2位=>4位。。。3位=>8位。。。4位=>16。。。5位=>32位。。。6位=>64位。。。7位=>128。。。8位=>256。。。9位=>512。。。10位=>1024位。。。1024字节等于1kB…=>20位=>1024*1024=1048576字节,即1024kB,1MB…=>30位=>1024*1024*1024=1073741824字节,即1048576 kB、1024MB和1GB……您将科学记数法和小数点与计算中使用的二进制/基数-2表示法相混淆。5x9=5x10^9=5000000000伙计们,他什么都没搞混。。。他只是给出了一个近似值,这是证据
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
from pathlib import Path
file = Path() / 'doc.txt'  # or Path('./doc.txt')
size = file.stat().st_size
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>
print (5368709120 >> 10)  # 5242880 kilobytes (kB)
print (5368709120 >> 20 ) # 5120 megabytes (MB)
print (5368709120 >> 30 ) # 5 gigabytes (GB)
#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 ....
import sys
print(sys.getsizeof(your_file))
nums = range(10000)
squares = [i**2 for i in nums]
print(sys.getsizeof(squares))
import os

res = os.stat(filename)

res.st_size # this variable contains the size of the file in bytes