脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python检测空间储存剩余大小和指定文件夹内存占用的实例

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

2021-03-03 00:33晓东邪 Python

今天小编就为大家分享一篇python检测空间储存剩余大小和指定文件夹内存占用的实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

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

?
1
2
3
4
5
6
7
8
9
10
11
12
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、检测指定路径剩余储存空间大小

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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 属性。

?
1
2
3
4
5
6
7
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检测空间储存剩余大小和指定文件夹内存占用的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/xiaodongxiexie/article/details/74545561

延伸 · 阅读

精彩推荐