美丽心灵公益论坛

查看: 1524|回复: 0

Python获取磁盘剩余空间

[复制链接]
累计签到:57 天
连续签到:1 天

981

主题

461

回帖

8037

积分

版主

Rank: 7Rank: 7Rank: 7

积分
8037
发表于 2022-4-11 11:38:04| 字数 1,846 来自手机 | 显示全部楼层 |阅读模式

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

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

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
"""
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|免责及版权声明|关于|美丽心灵公益论坛

GMT+8, 2025-9-19 13:05 , Processed in 0.037420 second(s), 26 queries .

Powered by Discuz! X3.4

!copyright!

快速回复 返回顶部 返回列表