Python获取磁盘剩余空间

电脑技术 电脑技术 1167 人阅读 | 0 人回复 | 2022-04-11

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
# get disk/flash drive information on Windows
# using the win32 extension module from:
# http://sourceforge.net/projects/pywin32/files/
# tested on Windows XP with Python25 and Python31 by vegaseat

import win32file
import os

def get_drivestats(drive=None):
    '''
    drive for instance 'C'
    returns total_space, free_space and drive letter
    '''
    # if no drive given, pick the current working directory's drive
    if drive == None:
        drive = os.path.splitdrive(os.getcwd())[0].rstrip(':')
    sectPerCluster, bytesPerSector, freeClusters, totalClusters = \
        win32file.GetDiskFreeSpace(drive + ":\\")
    total_space = totalClusters*sectPerCluster*bytesPerSector
    free_space = freeClusters*sectPerCluster*bytesPerSector
    return total_space, free_space, drive

# use default drive (current drive)
# or specify drive for instance C --> get_drivestats('C')
total_space, free_space, drive = get_drivestats()

print( "Drive = %s" % drive )
print( "total_space = %d bytes" % total_space )
print( "free_space  = %d bytes" % free_space )
print( "used_space  = %d bytes" % (total_space - free_space) )

print( '-'*40 )
mb = float(1024 * 1024)  # float() needed for Python2

print( "Drive = %s" % drive )
print( "total_space = %0.2f Mb" % (total_space/mb) )
print( "free_space  = %0.2f Mb" % (free_space/mb) )
print( "used_space  = %0.2f Mb" % ((total_space - free_space)/mb) )

print( '-'*40 )
gb = float(1024 * 1024 * 1024)

print( "Drive = %s" % drive )
print( "total_space = %0.2f Gb" % (total_space/gb) )
print( "free_space  = %0.2f Gb" % (free_space/gb) )
print( "used_space  = %0.2f Gb" % ((total_space - free_space)/gb) )

"""possible output -->
Drive = D
total_space = 59674370048 bytes
free_space  = 48973877248 bytes
used_space  = 10700492800 bytes
----------------------------------------
Drive = D
total_space = 56909.91 Mb
free_space  = 46705.13 Mb
used_space  = 10204.79 Mb
----------------------------------------
Drive = D
total_space = 55.58 Gb
free_space  = 45.61 Gb
used_space  = 9.97 Gb
"""
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则