python硬盘api-在Python中获取硬盘大小

I am trying to get the hard drive size and free space using Python (I am using Python 2.7 with macOS).

I am trying with os.statvfs("/"), especially with the following code.

Is it correct what I am doing? Which definition of the variable giga shall I use?

import os

def get_machine_storage():

result=os.statvfs("/")

block_size=result.f_frsize

total_blocks=result.f_blocks

free_blocks=result.f_bfree

# giga=1024*1024*1024

giga=1000*1000*1000

total_size=total_blocks*block_size/giga

free_size=free_blocks*block_size/giga

print("total_size = %s" % total_size)

print("free_size = %s" % free_size)

get_machine_storage()

EDIT:

statvfs is deprecated in Python 3, do you know any alternative?

解决方案

For Python 2 till Python 3.3

Notice: As a few people mentioned in the comment section, this solution will work for Python 3.3 and above. For Python 2.7 it is best to use the psutil library, which has a disk_usage function, containing information about total, used and free disk space:

import psutil

hdd = psutil.disk_usage("/")

print ("Total: %d GiB" % hdd.total / (2**30))

print ("Used: %d GiB" % hdd.used / (2**30))

print ("Free: %d GiB" % hdd.free / (2**30))

Python 3.3 and above:

For Python 3.3 and above, you can use the shutil module, which has a disk_usage function, returning a named tuple with the amounts of total, used and free space in your hard drive.

You can call the function as below and get all information about your disk"s space:

import shutil

total, used, free = shutil.disk_usage("/")

print("Total: %d GiB" % (total // (2**30)))

print("Used: %d GiB" % (used // (2**30)))

print("Free: %d GiB" % (free // (2**30)))

Output:

Total: 931 GiB

Used: 29 GiB

Free: 902 GiB

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值