python检测空间储存剩余大小和指定文件夹内存占用的实例

yipeiwu_com6年前Python基础

1、检测指定路径下所有文件所占用内存

import os
def check_memory(path, style='M'):
 i = 0
 for dirpath, dirname, filename in os.walk(path):
  for ii in filename:
   i += os.path.getsize(os.path.join(dirpath,ii))
 if style == 'M':
  memory = i / 1024. / 1024.
  print '%.2f MB' % memory
 else:
  memory = i / 1024. / 1024./ 1024.
  print '%.4f GB' % memory

2、检测指定路径剩余储存空间大小

import ctypes
import os
import platform
import sys
def get_free_space_mb(folder):
 """ Return folder/drive free space (in bytes)
 """
 if platform.system() == 'Windows':
  free_bytes = ctypes.c_ulonglong(0)
  ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(folder), None, None, ctypes.pointer(free_bytes))
  return free_bytes.value/1024/1024/1024 
 else:
  st = os.statvfs(folder)
  return st.f_bavail * st.f_frsize/1024/1024/1024.

这个适用于unix系统下,windows系统下 os 无 statvfs 属性。

def disk_stat(path):
 import os
 hd={}
 disk = os.statvfs(path)
 percent = (disk.f_blocks - disk.f_bfree) * 100 / (disk.f_blocks -disk.f_bfree + disk.f_bavail) + 1
 return percent
print disk_stat('.')

以上这篇python检测空间储存剩余大小和指定文件夹内存占用的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python求两个list的差集、交集与并集的方法

本文实例讲述了Python求两个list的差集、交集与并集的方法。分享给大家供大家参考。具体如下: list就是指两个数组之间的差集,交集,并集了,这个小学数学时就学过的东西,下面就以实...

11个并不被常用但对开发非常有帮助的Python库

11个并不被常用但对开发非常有帮助的Python库

近来,越来越多的数据科学家开始使用Python,我不由得想到,尽管他们从pandas、scikit-learn和numpy这些库中得到了不少好处,但是他们也许错过了一些也许较老但同样有帮...

win7上python2.7连接mysql数据库的方法

win7上python2.7连接mysql数据库的方法

 一:安装MySQL-python驱动 pip install mysql 二:连接到MySQL服务器的test数据库 #!/usr/bin/python #...

Python中AND、OR的一个使用小技巧

python中的and-or可以用来当作c用的?:用法。比如 1 and a or b,但是需要确保a为True,否则a为False,还要继续判断b的值,最后打印b的值。 今天看到一个好...

Python 实现文件打包、上传与校验的方法

不多说,我们直接上源码: # -*- coding:UTF-8 -*- ''' 实现文件打包、上传与校验 Created on 2018年1月12日 @author: liuyazh...