Fra*_*dan 74
import ctypes
import os
import platform
import sys
def get_free_space_mb(dirname):
"""Return folder/drive free space (in megabytes)."""
if platform.system() == 'Windows':
free_bytes = ctypes.c_ulonglong(0)
ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(dirname), None, None, ctypes.pointer(free_bytes))
return free_bytes.value / 1024 / 1024
else:
st = os.statvfs(dirname)
return st.f_bavail * st.f_frsize / 1024 / 1024
Run Code Online (Sandbox Code Playgroud)
请注意,您必须传递目录名称GetDiskFreeSpaceEx()才能工作(statvfs()适用于文件和目录).您可以从文件中获取目录名称os.path.dirname().
另请参阅文件os.statvfs()和GetDiskFreeSpaceEx.
jha*_*sse 26
使用安装psutilpip install psutil.然后您可以使用以下字节获取可用空间量(以字节为单位)
import psutil
print(psutil.disk_usage(".").free)
Run Code Online (Sandbox Code Playgroud)
Erx*_*xin 24
您可以将wmi模块用于windows,将os.statvfs用于unix
对于窗口
import wmi
c = wmi.WMI ()
for d in c.Win32_LogicalDisk():
print( d.Caption, d.FreeSpace, d.Size, d.DriveType)
Run Code Online (Sandbox Code Playgroud)
对于unix或linux
from os import statvfs
statvfs(path)
Run Code Online (Sandbox Code Playgroud)
shutil.disk_usage()与os.path.realpath('/')名称正则化一起使用:
from os import path
from shutil import disk_usage
print([i / 1000000 for i in disk_usage(path.realpath('/'))])
Run Code Online (Sandbox Code Playgroud)
要么
total_bytes, used_bytes, free_bytes = disk_usage(path.realpath('D:\\Users\\phannypack'))
print(total_bytes / 1000000) # for Mb
print(used_bytes / 1000000)
print(free_bytes / 1000000)
Run Code Online (Sandbox Code Playgroud)
为您提供总空间,已用空间和可用空间(以MB为单位)。
如果您不想添加另一个依赖项,您可以使用ctypes直接调用win32函数调用.
import ctypes
free_bytes = ctypes.c_ulonglong(0)
ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(u'c:\\'), None, None, ctypes.pointer(free_bytes))
if free_bytes.value == 0:
print 'dont panic'
Run Code Online (Sandbox Code Playgroud)
os.statvfs ()函数是获取类 Unix 平台(包括 OS X)信息的更好方法。Python 文档说“可用性:Unix”,但值得在您的 Python 构建中检查它是否也适用于 Windows(即文档可能不是最新的)。
否则,您可以使用pywin32库直接调用GetDiskFreeSpaceEx函数。
| 归档时间: |
|
| 查看次数: |
36263 次 |
| 最近记录: |