如何在python中检查⽂件⼤⼩?
我在Windows中编写脚本。 我想根据⽂件⼤⼩做⼀些事情。 例如,如果⼤⼩⼤于0,我将向某⼈发送电⼦邮件,否则继续其他操作。
如何检查⽂件⼤⼩?
#1楼
其他答案适⽤于实际⽂件,但是如果您需要适⽤于“类⽂件的对象”的⽂件,请尝试以下操作:
# f is a -like object.
f.seek(0, os.SEEK_END)
size = f.tell()
在我有限的测试中,它适⽤于真实⽂件和StringIO。 (Python 2.7.3。)当然,“类⽂件对象” 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楼
使⽤size :
>>> import os
>>> b = size("/path/isa_005.mp3")
>>> b
2071611L
输出以字节为单位。
#3楼
使⽤ ,并使⽤结果对象的st_size成员:
>>> import os
>>> statinfo = os.stat('')
>>> 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 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\"
print file_size(file_path)
结果:
6.1 MB
#5楼
使⽤pathlib ( 或在可⽤的pathlib ):
from pathlib import Path
file = Path() / ''  # or Path('./')
size = file.stat().st_size
这实际上只是os.stat周围的接⼝,但是使⽤pathlib提供了⼀种访问其他⽂件相关操作的简便⽅法。
python怎么读文件夹下的文件夹#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 ,
#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 ....

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。