本文實例講述了Python實現獲取磁盤剩余空間的2種方法。分享給大家供大家參考,具體如下:
方法1:
import ctypesimport osimport platformimport sysdef 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/1024print(get_free_space_mb('C://'),'GB')方法2:
import win32com.client as comdef TotalSize(drive):  """ Return the TotalSize of a shared drive [GB]"""  try:    fso = com.Dispatch("Scripting.FileSystemObject")    drv = fso.GetDrive(drive)    return drv.TotalSize/2**30  except:    return 0def FreeSpace(drive):  """ Return the FreeSpace of a shared drive [GB]"""  try:    fso = com.Dispatch("Scripting.FileSystemObject")    drv = fso.GetDrive(drive)    return drv.FreeSpace/2**30  except:    return 0workstations = ['dolphins']print ('Hard drive sizes:')for compName in workstations:  drive = '////' + compName + '//c$'  print ('*************************************************/n')  print (compName)  print ('TotalSize of %s = %f GB' % (drive, TotalSize(drive)))  print ('FreeSpace on %s = %f GB' % (drive, FreeSpace(drive)))  print ('*************************************************/n')運行效果如下圖:

更多關于Python相關內容感興趣的讀者可查看本站專題:《Python編碼操作技巧總結》、《Python數據結構與算法教程》、《Python Socket編程技巧總結》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答