如何在Python中获取文件的大小?
当前回答
严格地坚持这个问题,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>
其他回答
如果我想从字节转换到任何其他单位,我使用位移位技巧。如果右移10,基本上就是按一个数量级(倍数)移动。
例如:5GB为5368709120字节
print (5368709120 >> 10) # 5242880 kilobytes (kB)
print (5368709120 >> 20 ) # 5120 megabytes (MB)
print (5368709120 >> 30 ) # 5 gigabytes (GB)
严格地坚持这个问题,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>
使用pathlib(在Python 3.4或PyPI上可用的backport中添加):
from pathlib import Path
file = Path() / 'doc.txt' # or Path('./doc.txt')
size = file.stat().st_size
这实际上只是一个围绕os的界面。但是使用pathlib提供了一种访问其他文件相关操作的简单方法。
你可以使用os模块中的stat()方法。您可以为它提供字符串、字节甚至PathLike对象形式的路径。它也适用于文件描述符。
import os
res = os.stat(filename)
res.st_size # this variable contains the size of the file in bytes
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
推荐文章
- 每n行有熊猫
- 实例属性attribute_name定义在__init__之外
- 如何获取在Python中捕获的异常的名称?
- 第一次出现的值大于现有值的Numpy
- 如何从Python函数中返回两个值?
- 前一个月的Python日期
- Python中方括号括起来的列表和圆括号括起来的列表有什么区别?
- Python日志记录不输出任何东西
- 每n秒运行特定代码
- SQLAlchemy是否有与Django的get_or_create等价的函数?
- 如何将python datetime转换为字符串,具有可读格式的日期?
- 美丽的汤和提取div及其内容的ID
- 在Python中重置生成器对象
- 用Python构建最小的插件架构
- model.eval()在pytorch中做什么?